user3370394
user3370394

Reputation: 11

Array of pointers to a struct

typedef struct Oft{
   int   mode;
   int   refCount;
} OFT;

typedef struct proc{
   struct proc *next;
   int    uss, usp;
   int    pid;                // add pid for identify the proc
   int    status;             // status = FREE|READY|RUNNING|SLEEP|ZOMBIE    
   int    ppid;               // parent pid
   OFT    *fd[10];    
   int    kstack[1024];      // per proc stack area
}PROC;

How would I initialize and use my *fd[10] variable?

assume that I have

PROC *p;

Is this the correct way to initialize its *fd[10]?

for(i = 0; i < 10; i++)
{
    p->fd[i] = (OFT *) malloc (sizeof(OFT));
    (*p->fd)[0] = Some OFT object?   
}

why is p->fd[i] always equal to null when I do the following checking?

if (p->fd[i] == NULL)
    //Do sometiong

Upvotes: 1

Views: 75

Answers (1)

Guntram Blohm
Guntram Blohm

Reputation: 9819

p->fd[i] = malloc(sizeof(OFT));

is correct, as long as you've provided space for p to point to, by using malloc() or by making it point to some PROC variable. Note you don't need to cast, since malloc() returns a void * which is cast to any type of pointer automatically. You should, however, check if malloc() returns NULL.

(*p->fd)[0]

is wrong and will result in a compiler error. If you have an OFT object named myoft; you can assign it just like you did with malloc; of course, since fd[x] is a pointer, you want to have the address of the object:

p->fd[x] = &myoft;

If you want to access one of the components of one of your OFTs, you could, for example, use

p->fd[x]->refCount++;

I can't answer the last question, why if (p->fd[i] == NULL) is always true, unless you provide a complete example of your code.

Upvotes: 2

Related Questions