Search code examples
cmallocdynamic-memory-allocationcalloc

memory allocation in C for pointers


I'm trying to build a structure called PROCESS in C, this struct should contain the ID(id) and waiting time (wt) of the process.

typedef struct PROC{
    int id;
    int wt;
}PROCESS;

PROCESS *pt = NULL;

Now I want to make more then one instance of this struct like an array. what I want to do is something like this':

PROCESS pt[10];
pt[0].id = 5;
pt[1].id = 7;

But I want to do it using dynamic memory allocation:

pt = calloc(2,sizeof(PROCESS));

pt[0]->id = 5;

What is my mistake?


Solution

  • pt is a pointer to PROCESS, pt[0] is the first PROCESS object pointed to by pt. The -> operator to access members of a struct must be used with pointers only, otherwise use .

    pt[0].id = 5;
    

    would be correct.1

    An since you say you are doing C, you don't need to cast malloc or calloc.

    PROCESS *pt = calloc(2, sizeof *pt);
    if(pt == NULL)
    {
        // errror handling
        // do not continue
    }
    
    pt[0].id = 5;
    pt[1].id = 7;
    

    Also don't forget to check the return value of calloc and don't forget to free the memory later with free(pt);.


    Fotenotes

    1Note that this would be equivalent to

    pt->id = 5;
    

    but if you want to set id of the second element, you would need to do

    (pt+1)->id = 7;
    

    but I think it's more readable to do

    pt[1].id = 7;