I am new to coding and I'm currently learning about Divide et Impera. I want to calculate the sum of the elements from an array, and I thought I should start with writing a function that builds the array, but for some reason it's not working and i can't figure out why.
In your first code snippet, you pass n as argument, but then you immediately overwrite the value of n with the value read from std::cin. Why? And, in your second code snippet, where is variable n even defined?
If your intent was to "return" the value of n, you need a reference (or pointer).
Either way, how you do you ensure that your array v is large enough to hold (at least) n values ???
I think a correct implementation would be more like:
int *citire(int &n)
{
std::cin >> n; // ask number of elements to read
if (n > 0)
{
int *v = newint[n]; // dynamically allocate array of the required size !!!
for(int i = 0; i < n; i++)
{
std::cin >> v[i]; // fill array, element by element
}
return v; // return the array to caller; must be delete[]'ed by caller!
}
return NULL; // error
}
int main(void)
{
int n;
int *array = citire(n); // Note that 'n' is passed as a reference, so that it can be updated in the function!
if (array)
{
for(int i = 0; i < n; i++)
{
std::cout << array[i];
}
delete[] array;
}
}
int v[100], n;
void citire(int v[],int n)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>v[i];
}
}
int main()
{
citire(v,n);
//here comes function for the sum
return 0;
}
In the second case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int v[100], n;
void citire()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>v[i];
}
}
int main()
{
citire();
//function for sum
reuturn 0;
Ok, thank you so much!!! Now I understand!!! I gave it as an argument but then immediately overwrote it. I'm sorry for such mistakes... Still learning. But really thank you so much!!!