Error expected identifier or '(' int &arrayreturn[I] = {I}

Advertisements
#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?

>Solution :

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;
}

Leave a Reply Cancel reply