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?

4
  • Wouldn't the address of something be the result of applying the address-of operator? i.e., &a Commented Oct 24, 2012 at 18:41
  • 32 or 64 bit machine? i suspect 64 Commented Oct 24, 2012 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. 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. Commented Oct 24, 2012 at 18:48
  • You may want to have a look at the accepted answer to this question Commented Oct 24, 2012 at 19:21

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you ouah , for giving such a nice explanation......
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.