有人能解释一下为什么这段代码的输出是 2 吗?我误以为是 3。
int array[] = {1, 2, 3};
int *address = array;
array[0] = 2;
array[1] = array[2];
array[2] = *address;
printf("%d\n", array[2]);
return 0;
答案1
这个问题可能不太适合问这个。不过,答案如下:
*address
指向 ,array[0]
你往里面填入 2。然后,你把 的内容address
放入array[0]=2
array[2] 中,并打印出来。结果,你得到了 2。
答案2
int array[] = {1, 2, 3};
int *address = array; /* address storing arrays first byte address which is array[0] address*/
array[0] = 2; /* array[0]=1 is overwritten to array[0]=2 */
array[1] = array[2]; /* array[1]=2 is overwritten to array[2]=3 */
array[2] = *address; /* array[2]=3 is overwritten with element in address */
printf("%d\n", array[2]); /* printing array[2] value which is address which is indeed array[0] value */
return 0;
请发布您下一个与 c 和编程相关的问题堆栈溢出社区。https://stackoverflow.com/