3

Possible Duplicate:
Is array name a pointer in C?

I was running the following code

#include <stdio.h>

int main()
{
  int a[4] = {1,2,3,4};
  int (*b)[4] = &a;
  int k = sizeof(a);
  printf("\n\n%d\n\n", k);
  printf("a = %u, b = %u, *b = %u, data = %d", a, b, *b, **b);
  return 0;
}

I got the following output

a = 3485401628, b = 3485401628, *b = 3485401628, data = 1

Here I am assigning the address of a to b, as the type of b is int**, but in the output I am getting that the address pointed by the a is the same as the address pointed by b.

It seems little confusing to me. What is the explanation?

Community
  • 1
  • 1
priyaranjan
  • 379
  • 1
  • 4
  • 16
  • Wouldn't the address of something be the result of applying the _address-of operator_? i.e., `&a` – K-ballo Oct 24 '12 at 18:41
  • 32 or 64 bit machine? i suspect 64 – pm100 Oct 24 '12 at 18:43
  • On your last question about the subject, Carl suggested that you'd read up on pointers before asking here. Did you do that? I can't believe that you didn't find anything valuable that could help you on this. http://www.c-faq.com/ is a good starting point. Also please learn how to come up with a more precise question title. This would already be a good step for yourself to learn what your problem is. – Jens Gustedt Oct 24 '12 at 18:48
  • You may want to have a look at the accepted answer to this [question](http://stackoverflow.com/a/1641963/771663) – Massimiliano Oct 24 '12 at 19:21

2 Answers2

5

The value of array a is the pointer to the first element of the array a.

The value of pointer &a (which is the same value and type as pointer b) is the pointer to the array a.

They have the same value (but different types) as they both start at the same memory address. There is no padding possible at the beginning of an array.

When evaluated a is of type int * and &a is of type int (*)[4].

Note that the correct way to print the address of a pointer is to use conversion specifier p. E.g.,

/* And p requires the argument to be a void *, so use a cast if
 * it is not the case
 */
printf("%p %p\n", (void *) a, (void *) &a);
ouah
  • 142,963
  • 15
  • 272
  • 331
0

On expressions (such as an argument for printf) arrays are decayed to pointers (to their respective arrays), meaning that if "b" points to "a", on an expression, "a" will also be a pointer to "a" (the block of memory allocated for "a").

The way of accessing elements at runtime however (internally), is different. In this case, "b" would require an additional indirection.

imreal
  • 10,178
  • 2
  • 32
  • 48