Why is it that when we declare a structure pointer we need to allocate memory

struct A{
///
};
int main(void)
{
    struct A *var=(struct A*)malloc(sizeof(struct A));
//
//
}

but when we declare a structure variable we do not need to allocate any memory?

struct A var;

2 Answers

2
Faisal Rahman Avash On Best Solutions

This is true for any pointers, not just pointers to structures. The reason being, when you declare a variable (of type int, char or the type of some struct A), you tell the compiler to create a new variable/instance. So, the compiler automatically allocates memory for that variable. But when you are declaring a pointer to some int or some struct A, you are essentially telling the compiler that you need a reference to some variable, not an a new variable of that type entirely. To illustrate this:

struct A{};
int a,b; // New variable a and b
struct A c,d; // New variables c,d of type struct A

// Now take a look at this:

int *px;
px = &a; // px referencing to a, no new int variable created;
px = &b; // px referencing to b, no new int variable created;

struct A* py;
py = &c; // py referencing to c, no new struct A variable created;
py = &d; // py referencing to d, no new struct A variable created;

Now, if you just declare a pointer A* p, here p is not referencing to anything. So, if you want p to refer to a new instance of struct A, you have to write explicitly:

c
p = (struct A*)malloc(sizeof(struct A));
0
Ta Quang Tu On
  • struct A var declares a variable var on stack area of main memory with internal structure as declared in the struct A.

  • struct A * var also declares a variable var on stack area of main memory but the var is a pointer now, and as you may know, a pointer in C is used to store address of a variable, so the var need to know what is the address, the statment (struct A*)malloc(sizeof(struct A)); gives you the address.