Search code examples
carrayssizeof

size of array of pointers


i have a doubt regarding sizeof operator

Code 1:

int main()
{
    int p[10];
    printf("%d",sizeof(p));   //output -- 40
    return 0;
}

Code 2:

int main()
{
    int *p[10];
    printf("%d",sizeof(*p));   //output -- 4
    return 0;
}

in the first code p points to an array of ints. in the second code p points to an array of pointers. i am not able to understand why the first code o/p is 40 but 2nd code o/p is 4 thought both points to an array of the same size ?


Solution

  • The output of the following program will give you some hints and understanding about the size of a type and a pointer to a type.

    #include <stdio.h>
    
    int main(void)
    {
        int p1[10];
        int *p2[10];
        int (*p3)[10];
    
        printf("sizeof(int)   = %d\n", (int)sizeof(int));
        printf("sizeof(int *) = %d\n", (int)sizeof(int *));
        printf("sizeof(p1)    = %d\n", (int)sizeof(p1));
        printf("sizeof(p2)    = %d\n", (int)sizeof(p2));
        printf("sizeof(p3)    = %d\n", (int)sizeof(p3));
    
        return 0;
    }
    
    int p[10];      => 10 consecutive memory blocks (each can store data of type int) are allocated and named as p
    
    int *p[10];     => 10 consecutive memory blocks (each can store data of type int *) are allocated and named as p
    
    int (*p)[10];   => p is a pointer to an array of 10 consecutive memory blocks (each can store data of type int) 
    

    Now coming to your question:

    >> in the first code p points to an array of ints.
    >> in the second code p points to an array of pointers.
    

    You are correct. In the code:2, to get the size of the array where p points to, you need to pass the base address

    printf("%d", (int)sizeof(p));
    

    and not the following

    printf("%d", (int)sizeof(*p));   //output -- 4
    

    The following are equivalent:

    *p, *(p+0), *(0+p), p[0]
    

    >> what's the difference between p[10] and 
    >> (*p)[10]...they appear same to me...plz explain
    

    The following is the answer to your other question:

    int p[10];
     _________________________________________
    |   0   |   1   |   2   |         |   9   |
    | (int) | (int) | (int) |  ...    | (int) |
    |_______|_______|_______|_________|_______|
    
    
    int (*p)[10]
     _____________________
    |                     |
    | pointer to array of |
    |     10 integers     |
    |_____________________|