tags:

views:

1353

answers:

2

I have a pointer to integer array of 10. What should dereferencing this pointer give me?

Eg:

#include<stdio.h>

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?


}
+8  A: 

What you dereference is a pointer to an array. Thus, dereferencing gives you the array. Passing an array to printf (or to any function) passes the address of the first element.

You tell printf that you pass it an unsigned int (%u), but actually what is passed is an int*. The numbers you see are the addresses of the first element of the array interpreted as an unsigned int.

Of course, this is undefined behavior. If you want to print an address, you have to use %p and pass a void*.

Johannes Schaub - litb
Or you can cast to an appropriate integer type - such as uintptr_t from '`<inttypes.h>`' and use an appropriate format item, probably PRIuPTR (he says, working from a flaky memory).
Jonathan Leffler
litb, can you explain me what does "dereferencing gives you the array" mean? Is it again pointer to array? or is it the address of the first element?
chappar
Johannes Schaub - litb
To pass the actual integers, you will have to dereference twice: `**ptr`, or more wordy `(*ptr)[0]` for the first element.
Johannes Schaub - litb
I found this thread wondering why I was getting the address when I thought ptr[0] was dereferencing the pointer and not knowing that it was passing the first element of the array to the function printf. I tried both **ptr and (*ptr)[0] and I received "Invalid type argument of unary" and "Subscripted value is neither array nor pointer." Is there any other way to access the value of the array?
Crystal
+2  A: 

Thats why I love and hate C.

When you declare

int var[10];

a reference to var has type "pointer to int" (Link to C Faq Relevant's section)

and a reference to &var is a pointer to an array of 10 ints.

Your declaration int (*ptr) [10] rightly creates a pointer to an array of 10 ints to which you assign &var (the address of a pointer to an array of 10 ints) (Link to C Faq Relevant's section)

With these things clear (hopefully), "ptr" would then print the base address of the "pointer to the array of 10 ints"

"*ptr" would then print the "address of the first element" of "the array of 10 ints".

Both of them in this case are equal and thats why you see the same address.

and yes **ptr would give you 1.

Aditya Sehgal
ofcourse it would print these out correctly if you follow litb's advice. Use (void *) and %p when printing addresses.
Aditya Sehgal