Tim's
Tim's

Reputation: 93

How is the memory allocated when I declare a pointer of a structure in C

I want to know how the memory is allocated when I'm using a pointer to declare my structure.

struct car{
    int id;
    int age;
};

So if I'm right, for most the compilers, the structure size is 8 bytes because int(4B) x 2 = 8B.

Now the point I don't understand.

//1
struct car *ptr = malloc(sizeof(struct car));
//2
char buffer[4090];
struct car *ptr = buffer;
//3
struct car *ptr = malloc(1);

In these 3 cases the size of the *ptr is 8 sizeof(*ptr). Why? And how is it represented in the memory?

Upvotes: 1

Views: 121

Answers (2)

A.S.H
A.S.H

Reputation: 29332

sizeof(something) is nothing represented in memory. It is determined at compile time.

Since ptr is declared as a car*, sizeof(*ptr) is for the compiler the size of the car structure.

This does not depend on the value of ptr or where it is pointing at, even if it is null.

On the other hand, sizeof(ptr) (without the star) is the size of a pointer, which depends on the system (i.e. 8 Bytes on a Win 64-bit). In this case, the type of the pointee does not matter.

Upvotes: 2

The type of the expression *ptr is struct car, which is 8 by your own reckoning.

As to why all three cases say the size is 8 for the sizeof(*ptr): in all three cases, C thinks of your ptr variable as a pointer to a car struct, declared so by you. So it cannot treat those 3 different ptr variables differently, and neither will it treat *ptr differently. It does not matter whether it's a single car item (1 case), or one of many in an array (2nd case), or indeed a completely broken bit of one byte long memory which is not even full car struct (3rd case).

C trusts the programmer to make sure that whatever is pointed at is actually there.

Upvotes: 0

Related Questions