Question related to sizeof and pointer arithmetic

S

somenath

Hi All,

I have couple of questions regarding the behavior of the bellow code.
#include<stdio.h>
int main(void)
{
int ar[][3]={
{1,2},
{3,4},
{4,5}
};
printf("\n sizeof(int) = %d\n",sizeof(int));
printf("\n addr ar = %p \n",(void *) ar);
printf("\n sizeof(ar) = %d\n",(int) sizeof(ar));
printf("\n addr ar+1 = %p \n",(void *) (ar+1));
printf("\n addr *ar+1 = %d \n", **(ar+1));
printf("\n addr *ar = %d \n", **ar);
return 0;

}
Out put

sizeof(int) = 4

addr ar = 0xbfa21a3c

sizeof(ar) = 36

addr ar+1 = 0xbfa21a48

diff between (ar+1) and ar = 1

addr *ar+1 = 3

addr *ar = 1

According to my understanding is type of ar is int (* )[3][3] that's
the reason sizeof (ar) prints 3*3*sizeof(int) = 9*4 = 36;

So as according to pointer arithmetic ar+1 should point to next object
of type int (* )[3][3] .But in the current program address of ar is
0xbfa21a3c and address of ar+1 is 0xbfa21a48 .The diffrence between ar
+1 and ar is 3 *sizeof(int) .
Which indicates ar is of type int(*)[] not int (*)[][] .

How is it possible? Where am I going wrong?

Please help.

Regards,
Somenath
 
K

Kalle Olavi Niemitalo

somenath said:
According to my understanding is type of ar is int (* )[3][3] that's
the reason sizeof (ar) prints 3*3*sizeof(int) = 9*4 = 36;

No, the type of ar is int [3][3]. If it were int (*)[3][3], then
sizeof(ar) would be sizeof(int (*)[3][3]), which is typically 4
or 8, not 36.

int ar[3][3];
int (*arp)[3][3];
sizeof(&ar) or sizeof(arp) is the size of the pointer, typically 4 or 8.
sizeof(ar) or sizeof(*arp) is the size of the array, 3*3*sizeof(int).
arp = &ar could be assigned, although it doesn't matter to the sizeof.
So as according to pointer arithmetic ar+1 should point to next object
of type int (* )[3][3].

Not at all. In the expression ar+1, the array ar is converted to
a pointer that points to the first element of the array ar. The
type of this first element is int [3] and the type of the pointer
is int (*)[3]. ar+1 then is the address of the second element of
the array ar, i.e. the same as &ar[1]. The type of ar+1 too is
int (*)[3], a pointer to an array of three integers.

The conversion from an array to a pointer occurs in most
situations where an array is used, but sizeof is one of the
exceptions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top