Can anyone explain why the output of this code is 2? I mistakenly thought it was 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;
This is probably the wrong site to ask such questions. Nevertheless, here is the answer:
*address
is pointing to array[0]
which you fill with 2. Then, you put the content of address
, which is array[0]=2
into array[2], and print it. As a result, you get 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;
Please post your next qestions related to c and programming in Stackover flow community.https://stackoverflow.com/
This is not Ubuntu-related.
– thomasrutter Jul 16 '14 at 04:31