0

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;
jwhstman
  • 3
  • 2

2 Answers2

5

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.

noleti
  • 4,053
  • 27
  • 25
  • Ah I see, I get it now, I almost didn't post it but thanks for the answer, I'll post C and coding questions in the Stack overflow community. – jwhstman Jul 16 '14 at 04:11
3
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/

Sudheer
  • 5,113
  • 4
  • 24
  • 27