Problem with storing 10 integers into an array C++ - c++

Ok, I'm very confused as to why this happens. All I'm trying to do is put 10 integers from input into an array. Why is this happening.
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
If you could please tell me where I'm going wrong, that would be very much appreciated. Thank you!

From how your code is written, you're only adding the user's input to the [10] element of intArray[] within that for loop you created. Additionally, any information added to the array at intArray[10] or beyond is placed out of bounds.
The only way I can really demonstrate what I mean is...
for (int i = 0; i < 10; i++)
{
std::cout<<"Enter a number:";
std::cin >> intArray[i];
}
Another thing I noticed is you're creating another array with the same name in your printData method. You should instead pass the intArray you're filling up with information to this method and use it to display your information.

The problem lies in this block of code-
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
As mentioned in other answers and comments you are storing all the values in the 10th memory slot of the array.
As per your comment
I forgot to mention, the output is just random integers and characters. EX: 00B3F724
00B3F724=> These are the memory address allocated to the array and which will hold the elements which will be inserted.
How array actually works-
float myArray[10];
The above snip creates 10 units of memory space. The units differ on the type which the array will hold. In this case it is holding float values, so each memory space will be of 4 bytes. All of these spaces have an address for lookup and other operations. All these spaces are expecting a float value to be inserted.
As you are using the loop you have to loop through the array(all the memory slots allocated to the array) and allocate a float element to each one of them and not only the last element(10th).
Effectively your for loop will become
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
Instead of intArray[10] insert values like this intArray[i]. As i will traverse through all the slots on every iteration of the loop insert a values to a slot.
Your code will look like
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}

As you know if an array is declared as myArray[10], its index ranges from 0-9. Putting a value in myArray[10] will go out of bound and will produce garbage value.
In getData(float intArray[]) you are always overwriting the content of intArray[10] while it is out of bound so it is not being stored in an actual array. You should write your getData(float intArray[]) as following :
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cin >> intArray[i];
}
return 1;
}
Also in printData(float intArray[10]) you are only printing the base address of the array (i.e the name of the array gives the address of the 0th index).So the correct code would be:
void printData(float intArray[])
{
for(int i=0;i<10;i++)
{
cout << intArray[i]<<" ";
}
}

Simply change,
std::cin >> intArray[10];
to,
std::cin >> intArray[i];
What you are doing wrong:
you are storing the value at the 10th position (actually it is 11th position) again and again and the value at 10th position replaces with the new value again and also the 10th position doesn't exist in the array because the index of the array starts from 0, so your array has the index values from 0 to 9.

Related

Run-Time Check Failure #2 - Stack around the variable 'sortObject' was corrupted. how to fix?

I was trying to store numbers in an array. The first half of the array are numbers that are ascending 1,2,3,4,5 etc and the second half of the array are random numbers. When i run the program it produces the output I wanted but gives me the error please help
#include <iostream>
#include <cstdlib>
using namespace std;
class sorting {
private:
int size, elements;
int arr[NULL];
public:
void sort(){
cout << "Enter number of desired elements" << ">"; cin >> elements;
arr[elements];
half();
}
void half() {
for (int i = 0; i < elements/2; i++) {
arr[i] = i + 1;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = rand();
}
cout << "This is the elements of the array";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
};
int main()
{
sorting sortObject;
sortObject.sort();
return 0;
}
As i could see you want the array size to change during run time depending on the input, we need to dynamically allocate a array.so take a integer pointer as a field instead of static array.
then inside the sort function after reading the input, dynamically allocate the memory to pointer.(actually its better if we do it in a constructor).
int *arr;
arr=(int *)malloc(elements*sizeof(int));

Some test cases aren't passing

#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.

Variable length array c++ & No operator >> error?

going through a c++ course and was asked to create a simple program to average values in a user array
i figured id go the extra mile and learn to mess with a few additional types.
I searched online for a fix for the non variable arrays in c, and i know this is where shit hits the fan
//manually allocate the space to the array
int** MyArray = new int* [Length_Of_Array]; // i changed it to float to suit my program
For my error's im getting
ERROR IMAGE
Is there a better alternative to this (sticking to arrays as opposed to vectors) ?
MY FULL CODE
#include <iostream>
using namespace std;
//function declare
float Avg(float Array, int Length);
//Variable declare
int Length_Of_Array;
int main()
{
//Declarations
float Result{};
//User defines size of the array
cout << "Please enter the length of your array (Min 5) ";
cin >> Length_Of_Array;
//User Enters x elements into array
cout << "Please enter" << Length_Of_Array << " Digits into the array " << endl;
//manually allocate the space to the array
float** MyArray = new float* [Length_Of_Array];
//Function use
Result = Avg(MyArray, Length_Of_Array);
//Result
cout << "THE AVERAGE OF YOUR ARRAY IS " << Result << endl;
}
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
Let's take a look at this function:
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
The type of Array is float** so the type of Array[i] is float *. But you can't read a float * from std::cin and you don't need a float** for a 1D-array. (** is usually used for matrices) Since you are required to use arrays, all you have to do is to change float** to float*.
So you get float Avg(float* Array, int length) and float* MyArray = new float[Length_Of_Array];
Some other hints:
Don't forget to update the forward declaration of Avg also ;)
Don't forget to free the allocated memory if you don't need it anymore with delete[] MyArray;
You should initialize a variable with an actual value like int sum = 0; insted of int sum{};. It makes your code better readble und understandable.
The function signature in function definition and declaration doesn't match.
float** Array means array of array or a pointer to array. Besides you have problem with memory leakage.
You can simply use vector instead:
float Avg(std::vector<float>& Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
and:
std::vector<float> MyArray(Length_Of_Array);

How to return the number of values input into an array?

At the moment, I am stumped and cannot progress on this problem. Any help or guidance would be greatly appreciated. The first part is working, however when I try to return the # of user inputs in the second part I get a Segmentation Fault. Below are the descriptions of both parts::
P2.1 Write a program consisting of main and displayArray functions. The main function declares an integer array with 10 elements and at the same time initializes them with up to 10 arbitrary values. The main function then calls displayArray function to display the contents of the array.
P2.2 Expand P2.1 with an additional fillArray function that prompts the user to enter up to 10 (size of the array) integers. Since a statically allocated array is often partially filled with values less than the actual size or storage capacity of the array (10 in our case), so the fillArray function must return a positive integer value representing the actual # of input values entered by the user.
#include <iostream>
using namespace std;
int displayArray(int arr[]);
int fillArray(int newArray[], int &inputs);
const int size = 10;
int main() {
int x, inputs = 0;
int arr[size] = {0,1,2,3,4,5};
int newArray[] = {};
displayArray(arr);
cout << "Enter .5 when finished. ";
fillArray(newArray, inputs);
cout << inputs;
cin >> x;
return 0;
}
int displayArray(int arr[]) {
for (int i = 0; i < size; i++)
cout << arr[i] << " " << endl;
}
int fillArray(int newArray[], int &inputs) {
for(int i = 0; ; i++) {
cout << "Enter an integer: " << endl;
cin >> newArray[i];
if(newArray[i] == .5) {
inputs = i + 1;
return inputs;
break;
}
}
}
You do not reserve memory for your newArray, since int newArray[] = {} will allocate an array of size 0 (actually not even defined as far as I know). So when calling fillArray, you will exceed array bounds.
Write
int newArray[10] = { 0 }
and it should at least work if you do not enter more than 10 values then.
Further, in fillArray, to not run out of bounds, I'd write...
int fillArray(int newArray[], int &inputs) {
for(inputs = 0; inputs < 10 ; inputs++) {
cout << "Enter an integer: " << endl;
cin >> newArray[i];
if(newArray[i] == 0) {
break;
}
}
inputs++;
return inputs;
}
Note further that the newArray[i] == .5 is at least misleading, since newArray is of type int and .5 is a floating point value. It will never evaluate to true, since the integral value newArray[i] will be converted to a float before comparison, and this conversion will never result in 0.5.

How to pass arrays in the main func. w/ c++

#include <iostream>
using namespace std;
const int MAX = 1000;
int ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;
void accept(int ArrMix[MAX])
{
cout<<"Enter the number of elements in your array: ";
cin>>r;
for (int i = 0; i < r; i++)
{
cout<<"Enter value:";
cin>>ArrMix[i];
}
}
void process(int &i)
{
if(ArrMix[i] >= 0)
{
ptrArrPos[PosCounter] = &ArrMix[i];
PosCounter++;
}
else
{
ptrArrNeg[NegCounter] = &ArrMix[i];
NegCounter++;
}
}
void display(int &i)
{
cout<<"Your passed array is: " << endl;
cout<<ArrMix[i] << endl;
cout <<"Total number of positive integers is: "<<PosCounter<<endl;
cout<<"Your positive array is: "<<endl;
for (int i = 0; i < PosCounter; i++)
{
cout << *ptrArrPos[i] << endl;
}
cout<<endl;
cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
cout<<"Your negative array is: "<<endl;
for (int i = 0; i < NegCounter; i++)
{
cout << *ptrArrNeg[i] << endl;
}
}
int main ()
{
int *i;
int a = &i;
accept(&ArrMix[MAX]);
process(a);
display(a);
system("pause>0");
}
The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array.
I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?
The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.
Passing an array is as simple as passing any other argument:
accept(ArrMix);
You also have a problem here:
int *i;
int a = &i;
You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.
It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.