Is [n] really interchangeable with * (a + n) - why sizeof returns two different answers?

I have a problem understanding one thing in C. I read in "ANSI C" that expressions such as a[n], where ais an array are really equivalent *(a+n). So, here is a small piece of code that I wrote to verify that:

#include <stdio.h>
int main(void)
{
    int a[10] = {0,1,2,3,4,5,6,7,8,9};
    int *p = a;
    printf("sizeof a: %d\n", sizeof(a));
    printf("sizeof p: %d\n", sizeof(p));
    return 0;
}

After executing the code, the program produces:

sizeof a: 40
sizeof p: 8

I do not understand - what have I just done? How aand pdifferent objects? (Judging by the output of the sizeof function)

+4
source share
2 answers

According to the C standard (6.5.3.4 sizeof and alignof operators)

2 sizeof ( ) , . . . - , ; .

, a, 10 , , 40 , 4 ( sizeof (int) 4).

int a[10] = {0,1,2,3,4,5,6,7,8,9};

p a

int *p = a;

, , 8 .

int *p = a;

int *p = &a[0];
+5

, a[n] *(a+n). .

a , 10 int , p - int*. , , a[5] *(a+5; int 5. .

a p , C , , . sizeof a 10 * sizeof (int), sizeof p sizeof (int*) ( int).

, , , . :

int *p = a;

a - . &a[0], p. a p ; ( , ) a. sizeof , ; sizeof a , .

6 comp.lang.c FAQ.

+3

All Articles