views:

35

answers:

1

I haven't used C in 5-6 years, and feel that this is probably a really obvious answer.

I thought that arrays were passed by reference automatically in C, so my code below should modify the values of the array created in main() within the change function. It changes the values of the local variable within the change function, but this is not reflected afterwards in the main function.

Here is my code for my example:

int main(){
int array[3][5];
int i;
int j;\

printf("BEFORE (MAIN):\n");
for(i = 0; i < 3; i++){
 for(j = 0; j < 5; j++){
  array[i][j] = 1;
  printf("%i, ", array[i][j]);
 }
}
printf("\n\n");
change(array);
printf("\n");

printf("AFTER (MAIN):\n");
for(i = 0; i < 3; i++){
 for(j = 0; j < 5; j++){
  array[i][j] = 1;
  printf("%i, ", array[i][j]);
 }
}
printf("\n");

return 1;
}

void change(int array[][5]){
printf("PRECHANGE (CHANGE):\n");
int i;
int j;
for(i = 0; i < 3; i++){
 for(j = 0; j < 5; j++){
  printf("%i, ", array[i][j]);
 }
}

printf("\n\n");
printf("AFTER CHANGE (CHANGE):\n");

for(i = 0; i < 3; i++){
 for(j = 0; j < 5; j++){
  array[i][j] = 0;
  printf("%i, ", array[i][j]);
 }
}
printf("\n");
}

The output is as follows:

BEFORE (MAIN): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

PRECHANGE (CHANGE): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

AFTER CHANGE (CHANGE): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

AFTER (MAIN): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

I would have thought it should be this:

BEFORE (MAIN): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

PRECHANGE (CHANGE): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,

AFTER CHANGE (CHANGE): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

AFTER (MAIN): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

+1  A: 

If you set the value to 1

printf("AFTER (MAIN):\n");
for(i = 0; i < 3; i++){
 for(j = 0; j < 5; j++){
  array[i][j] = 1;                  /* set to 1 and print afterwards */
  printf("%i, ", array[i][j]);
 }
}

why do you expect 0 to be printed?

pmg
Good Point! FFS! Now to try it on my real program and see why that wasn't working.