1

I used address of operator on top of derefrence operator. Can you please explain what is happening behind the scenes.

Here is my code:

#include <stdio.h>

int main(void)
{
    int arr[10];
    printf("Enter number into an array:\n");
    for(int i = 0; i < 10; i++)
    {
        /* in next line I use address of operator
         * on top of derefrence operator
         * it still works! why?
         */
        scanf("%d", &(*(arr+i)));
    }
    for(int i = 0; i < 10; i++)
    {
        printf("%d", arr[i]);
    }
    return 0;
}
2

From the inside out:

  • (arr + i) is a pointer to the i'th element of arr
  • *(arr + i) is the contents of the pointer to i'th element of arr (dereferenced (arr + i))
  • &(*(arr + 1) is the address of the contents of the pointer to i'th element of arr (which is the same "address" as (arr + i))

Maybe you got to this point because scanf("%d", arr[i]); wouldn't compile with this error error: format specifies type 'int *' but the argument has type 'int'

From man scanf:

the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format.

Therefore, that second argument needs to be a pointer. arr + i would work because it's a pointer; *(arr + i) does not work because it's an integer, &(*(arr + i)) works because it's the address of an integer. (&arr[i] would work too)

This arr[i] might be described as syntactic sugar for this *(arr + i).

You can get a helpful visual of this if you use debug50. Set "Watch Expressions" for each of arr + i, *(arr + i) and &(*(arr + i))

2
  • I know arr + i is a pointer or an address but *(arr + i) is value at that address. This implies that &(*(arr + i)) is refrencing to a value and not a variable! And we can't reference a value. &(69) won't work! It seems I am lost! @DinoCoderSaurus Oct 8 '16 at 11:52
  • I "translate" &(expression) as "the address of expression". &(69) doesn't work, because 69 is a constant; there is nothing to reference or dereference. It just "is". If you had something like int n = 69;, then &n would work. Oct 8 '16 at 12:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .