What is the sizeof the pointer pointing to a structure variable?

Viewed 415

I am trying to print the size of pointers in both the cases. For both the cases I am getting 8 16 as output.

#include <stdio.h>

struct Book
{
    char name[10];
    int price;
};

int main(void)
{
    struct Book a;      // Single structure variable
    struct Book* ptr;   // Pointer of Structure type

    ptr = &a;

    struct Book b[10];  // Array of structure variables
    struct Book* p;     // Pointer of Structure type

    p = &b;

    printf("%ld %ld\n",sizeof(ptr),sizeof(*ptr));
    printf("%ld %ld\n",sizeof(p),sizeof(*p));

    return 0;
}
2 Answers

First of all, sizeof operator yields a type size_t, you must use %zu to print that.

Then, usually in any architecture, the size of a pointer is always constant, irrespective of the type they point to. In other words, a pointer needs to hold a memory location, and for any normal architecture, the address (of a memory location) has a fixed size. So, the size of any pointer, is same.

Is this what you want, in the second case:

printf("%zu %zu\n", sizeof(p1), sizeof(*p1));
// Output
8 160

Okay! Let's start from the beginning.

As Sourav Ghosh stated in his answer, "A pointer needs to hold a memory location, and for any normal architecture, the address (of a memory location) has a fixed size. So, the size of any pointer is the same.", regardless of its data type which it points to.

Now coming to your problem, consider and try to understand this modified version of your program:

#include <stdio.h>

struct Book
{
    char name[10];
    int price;
};

int main(void)
{
    struct Book b[10];  // Array of structure variables
    struct Book* p;     // Pointer to type struct Book
    struct Book (*p1)[10]; // Pointer to type struct Book[], which is array of type struct Book

    p = b; // same as p = &b[0] but not as p = &b
    p1 = &b; // this is how assignment of a pointer to array is done

    printf("%zu %zu\n", sizeof(struct Book*), sizeof(struct Book));
    printf("%zu %zu\n",sizeof(p),sizeof(*p));
    printf("%zu %zu\n",sizeof(p1),sizeof(*p1));

    return 0;
}

Output:

// perhaps on your PC
8 16
8 16
8 160
// on my PC
4 16
4 16
4 160

You see in the output that sizeof(struct Book), sizeof(p), and sizeof(p1), all are the same. Thus, size of any type of pointer is the same.

But when you are printing the size of the struct Book, i.e. you are asking the compiler, "tell me how much bytes of memory this struct Book contains",

for the first two cases (sizeof(struct Book) or sizeof(*p)), it is 16 and for the last case it is 160 which is size of 10 variables of type struct Book.

And if you're wondering why 16 as the size of a variable of type stuct Book, that's because of the 2 padding bytes in between the char and int member.

Read this SO question about padding and packing in structures.

Related