Originally Posted by
transgalactic2
i know that &array_ptr[1] is the address of cell "1"
Correct (sort of, it's actually the second cell).
Originally Posted by
transgalactic2
if we want to print the value of cell one
we need to use *array_ptr[1] (this one points to the value)
Incorrect... array_ptr[1] is the value stored in cell two (array's are zero based so array_ptr[0] is actually the value stored in the "first" cell). array_ptr is a pointer to int, array_ptr[1] is the value in cell one, *array_ptr[1] does not make any sense in this context (maybe if array_ptr was declared as int **array_ptr or int *array_ptr[10] or somesuch it would).
Originally Posted by
transgalactic2
but when we just want to print array_ptr[1] we will get the address to which
array_ptr[1] is pointed to
No, as stated before, array_ptr[1] does not represent an address but rather a value at some address. array_ptr+1 on the other hand (or alternately, &array_ptr[1]) represents the address of the second cell.
Originally Posted by
transgalactic2
so i cant understand why when we execute this line:
Code:
printf("%i\n", array_ptr[1]);
we get the value to which the pointer is pointed to
instead of the address of the cell to which the ponter is pointed too
??
Again, as stated, array_ptr[1] is the value located at an address which is why you get said value as output.
[edit]
Code:
int array[4] = { 24, 36, 48, 64 };
int * array_ptr = &array[1];
printf("array_ptr[1] is : %d\n",array_ptr[1]);
printf("*(array_ptr+1) is: %d\n",*(array_ptr+1));
printf("array_ptr+1 is : %p\n",array_ptr+1);
printf("&array_ptr[1] is : %p\n\n",&array_ptr[1]);
printf("array[2] is : %d\n",array[2]);
printf("*(array+2) is : %d\n",*(array+2));
printf("array+2 is : %p\n",array+2);
printf("&array[2] is : %p\n",&array[2]);
Sample output on my machine:
Code:
array_ptr[1] is : 48
*(array_ptr+1) is: 48
array_ptr+1 is : 0012FF5C
&array_ptr[1] is : 0012FF5C
array[2] is : 48
*(array+2) is : 48
array+2 is : 0012FF5C
&array[2] is : 0012FF5C
[/edit]