#include "stdio.h"
int printsomething(int *array, int arrayreturn[5]) {
int i;
for(i = 0; i < 10; i) {
printf("%d\n", array[i]);
}
for(i = 0; i < 5; i) {
int &arrayreturn[i] = {i};
}
return 0;
}
int main() {
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// int *arraypointer = &array;
int arrayp[5];
int i;
printsomething(array, arrayp);
for(i = 0; i < 5; i) {
printf("%d\n", arrayp[i]);
}
return 0;
}
I am learning C and right now just playing with arrays and pointers trying to get comfortable. This bit of code has the goal of passing an array to a function, which was successful before I added the second part. That second part being assigning values in the called function to an already initialized array. Since we can't directly return an array I understood this was the way to do it. What exactly do you all think is going wrong here? And I just completely off the target?
CodePudding user response:
If you want to assign values to the array elements you need to use []
to access the elements and =
to assign them. I cannot really explain your code because it is unclear how you came to the conclusion that you need to write int &arrayreturn[i] = {i};
. Your loop can be this:
for(i = 0; i < 5; i) {
arrayreturn[i] = i;
}
CodePudding user response:
the first problem is that when you have a parameter of the form int arrayreturn[5]
you actually just pass an int pointer not an entire array of 5 elements. int arrayreturn[5]
and int *arrayreturn
compile to exactly the same cpu instructions. I never use the int arrayreturn[5]
syntax because i think it is confusing so i rather just pass a pointer and this is common practice as far as i know.
secondly in the second part of your code you try to declare a new array of size i by calling int &arrayreturn[i] = {i}
this is not possible because of multiple reasons mostly because you cant dynamically allocate arrays on the stack. it should be arrayreturn[i] = i