Hello,

I am learning C by reading the second edition of "The C Programming Language" by K&R but am struggling to understand this bit of code on page 145:

struct nlist *np;

if ((np = lookup(name)) == NULL){

   np = (struct nlist *) malloc(sizeof(*np));
.....
}

Lookup returns a pointer to a struct object with the given name value or NULL if not found. My understanding of sizeof is that it returns the size of a given object or type.

Given that the statement within the if block is only executed if np is assigned to NULL, I don't understand why you are allowed to dereference np to get to a non-existent struct nlist object before invoking sizeof on it?

Thanks for your help.

Gavin

sizeof(*np) is NOT dereferencing the pointer. The sizeof is an operator that is expanded at compile time, not runtime. *np is just getting the type of object that np was declared as, in this case struct nlist. sizeof(*np) is just another way of saying sizeof(struct nlist). Programmers like to use *np there so that the sizeof operator will be correct for anything declared as np -- such as if you change it from struct nlist to int.

Thanks for your reply. I should have realised sizeof was evaluated at compile time and not runtime.

Am I correct in thinking that sizeof(np) would give the sizeof a pointer to struct nlist, rather than a struct nlist itself?

Yes, that is correct.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.