0

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

Edited by gavindoc: n/a

2
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

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.

Edited by Ancient Dragon: n/a

0

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?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.