I have created a struct like this
struct PCB
{
int used;
char PID[1];
struct RCB *Other_Resources;
char type[10];
struct PCB **list;
struct PCB *parent;
struct PCB *children;
struct PCB *next;
int priority;
};
then I declared an array of struct PCB * like this
struct PCB *PCBLIST[1024];
my question is do I need to malloc the array of struct pointers in order to use those pointers? I read on another question on here that I should do something like this:
PCBLIST = malloc(1024 * sizeof(struct PCB *));
this is modified slightly, I think in the original question they used MAX instead of giving the actual value like I did 1024.
The error I am getting from gcc c99 is:
error: assignment to expression with array type
but if I try to access an individual struct pointer like with PCBLIST[i]->used I get a seg fault. Can someone shed some light on what I am doing wrong?
You don't need to dynamically allocate the array as that is already allocated by the declaration of the array. You need to allocate struct memory for each of the array entries to point to. Something like:
int ix;
for (ix = 0; ix < sizeof(PCBLIST) / sizeof(PCBLIST[0]); ix++) {
PCBLIST[ix] = malloc(sizeof(struct PCB));
}
Note that that allocates memory for all the entries of the array. If all the entries are always used then a simpler way would be to use a static allocation by declaring the array as an array of structs rather than an array of pointers to those structs:
struct PCB PCBLIST[1024];
That simplies things by not requiring dynamic allocation. But at the cost of potentially using more memory as it does not allow for a sparsely populated array (not all entries allocated). Which one is best to use depends on how you intend to use the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With