Matt Belle
Matt Belle

Reputation: 59

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?

Upvotes: 0

Views: 109

Answers (2)

Pablo
Pablo

Reputation: 13570

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;

Upvotes: 5

Anders Cedronius
Anders Cedronius

Reputation: 2076

typedef struct process{
    int id;
    int wt;
}processes;

I would allocate like this->

int numberOfDynamicStructs=2;

processes* myProcesses= calloc(numberOfDynamicStructs,sizeof(processes));

Write->

myProcesses[0].id=1;
myProcesses[1].id=2;

Read->

printf("%d %d",myProcesses[0].id,myProcesses[1].id);

Free when done..

/A

Upvotes: 0

Related Questions