Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dereferencing pointer to integer array

Tags:

c

pointers

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?


}
like image 919
chappar Avatar asked Jul 05 '09 05:07

chappar


1 Answers

When you declare

int var[10];

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

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 hopefully clear, 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.

like image 107
Aditya Sehgal Avatar answered Oct 05 '22 13:10

Aditya Sehgal