1
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
2
  • 1
    You must initialize p first before you initialize its members. Also check the return value of malloc. Commented Mar 2, 2014 at 10:17
  • Assume that I initialized it. I don't want to post more code that necessary Commented Mar 2, 2014 at 18:43

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

if I do p->fd[x] = &myoft in a function and exit that function and check one of its components after, it returns values different from the ones that I assigned! Any idea?
Oh I just realized that the return value of malloc is NULL. I did check p->fd[i] after malloc and it's still null!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.