dereferencing pointer to integer array

0 votes
asked Jul 5, 2009 by chappar

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?


}

3 Answers

0 votes
answered Jul 5, 2009 by johannes-schaub-litb

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*.

0 votes
answered Jul 5, 2009 by aditya-sehgal

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.

0 votes
answered Jul 11, 2013 by bluedroid

I guess this could bring more clarity :

(I'm just using a snippet of code to reduce clutter)

Declaration:

int a[5];
a[5] = {0,1,2,3,4);

Indirection

ptr = a   <======>  ptr = &a[0]

Dereferencing

*ptr = *a <======> *ptr = *&a[0]
                   *ptr =   a[0]

therefore, we can write:

*(ptr + i) = *(a + i) <======> *(ptr + i) = a[i]

NOTE: '<=====>' is just a sign for 'implies'. Nothing special!!! Hope I'm not wrong??

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...