Home > other >  dereference pointer to an array
dereference pointer to an array

Time:08-10

I have a basic doubt, when we de-reference a pointer to an array why we get name of the array instead the value of first member of an array, I see this has been asked here but I didn't get it exactly how?

dereferencing pointer to integer array


main()
{
    int var[10] = {1,2,3,4,5,6,7,8,9,10};
    int (*ptr) [10] = &var;

    printf("value = %u %u\n",*ptr,ptr);  //both print 2359104. Shouldn't *ptr print 1?


}

So, is it like when we dereference a pointer, it cancel out the reference operator and what we get is variable name, and in case of pointer to an array, it is the array name ?

main()
{
   int a = 10;
   int *p = &a;

   printf("%d\n", *p) /* p = &a; *p = *(&a); and having a dereference cancel out the &, gives us *p = a ? */
}

CodePudding user response:

Because ptr has type int (*)[10] which is a pointer to an array, *ptr has type int[10] which is an array type.

This array decays to a pointer to its first element when it is passed to printf which then prints the pointer value. The result would be the same if you passed var to printf instead of *ptr.

CodePudding user response:

You do not get a variable name when you dereference a pointer. If the pointer points to an object the you get that object. If it does not point to an object then you get undefined behavior. In particular, if the pointer points to a whole array, then you get that array. That's a fundamental aspect of how pointers work.

However, a fundamental aspect of how arrays work is that in most contexts, an expression of array type is automatically converted to a pointer to the first array element. This address corresponds to the address of the array itself, but has different type (int * in your case, as opposed to int (*)[10]). Typically, converting these to an integer type produces the same value. Thus, in your example code, *ptr is equivalent to var, and each is automatically converted to a pointer of type int *, equivalent to &var[0].

But note also that it is not safe to convert pointers to integers by associating them with printf directives, such as %u, that expect a corresponding integer argument. The behavior is undefined, and in practice, surprising or confusing results can sometimes be observed. One prints a pointer value with printf by using a %p directive, and converting the pointer value to type void *. Example:

    printf("pointer = %p %p\n", (void *)*ptr, (void *)ptr);

Combined with the type and value of ptr from your example, this can be expected to reliably print two copies of the same hexadecimal number.

  • Related