Search code examples
cpointersstructure

allocating memory for structure pointers


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;

Solution

  • 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));