0
[solved] Why my code won't work with array size over 6?
https://code.sololearn.com/c56jFiLzVm2h/?ref=app Hi. This code is supposed to calculate the sum of an array given by the user. Array size and numbers both with input from user. The problem occurs when the array size is over 6. It won't return the correct sum. Can anyone help me please and explain what I did wrong. Thank you!
9 Respuestas
+ 5
Anna Thank you.
+ 4
arr[0] = i;
I am not sure what you want to do at this line.
i should be the size of your array, but you put i into your array at index 0.
+ 4
int i;
cin >> i;
int arr[i]; ...
remove the line arr[0] = i;
First you get a number for i. Then you can create an array with a size of i.
edit:
int i; int arr[i] --> I think this creates an array with size = 0, because i has no value at this time. After that you can not change the size. Arrays have a fixed size.
+ 4
cin >> i;
int arr[i];
That doesn't work. The size of an array has to be a constant expression and determinable at compile time. You might be iterating over arbitrary memory slots that have nothing to with your array and adding garbage values
You can make a dynamic array like this:
int *arr = new int[i];
/* (...) */
delete[] arr;
(plus there are better alternatives in C++ >=11)
+ 4
Sorry for given a wrong answer. I have read only the lesson about arrays and not this: https://stackoverflow.com/questions/28625465/c-creating-an-array-with-a-size-entered-by-the-user
+ 3
Lucian Your welcome :)
+ 2
Thanks mate. I did what you said and it works fine now.
+ 2
Anna
int i;
cin >> i;
int arr[i];
At this time the array is filled with garbage values? I only checked arr[0]. (it was something like this 14224682)
After this loop
for ( x=0; x<i; x++)
{
cin >>arr[x];
sum+=arr[x];
}
the array is filled with the correct values. Can you explain why? Or what really happens?
Thanks.
+ 1
The contents of the array depend on where and how it was declared and initialized. If it has global scope (declared outside of main() and all other functions), it will be initialized with zeros. If declared in main() or any other function, it will be filled with garbage values unless it is initialized:
global scope:
int n[10]; // automatically initialized with zeros
local scope:
int n[10]; // garbage values, might contain zeros or other arbitrary numbers
int n[10]{}; // initialized with zeros
int n[10] = {}; // same
int n[10] = {1}; // first value is 1, all other values are zeros
int n[10] = {1, 2}; // n[0] = 1, n[1] = 2, n[2-9] = 0
https://code.sololearn.com/cZI0znL373K2/?ref=app