# Question related to sizeof and pointer arithmetic

Discussion in 'C Programming' started by somenath, Dec 23, 2007.

1. ### somenathGuest

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

sizeof(ar) = 36

diff between (ar+1) and 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?

Regards,
Somenath

somenath, Dec 23, 2007

2. ### Kalle Olavi NiemitaloGuest

somenath <> writes:

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

Kalle Olavi Niemitalo, Dec 23, 2007