开发者

Passing/modifying multidimensional array to function in C

开发者 https://www.devze.com 2023-01-22 03:45 出处:网络
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

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,


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消