Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting NULL to a struct pointer in C?

Is there any benefit of casting NULL to a struct pointer in C ?

For example:

typedef struct List
{
....
} List;

List *listPtr = ((List *) NULL) ;

Example from PostgreSQL source:

#define NIL                     ((List *) NULL)

http://doxygen.postgresql.org/pg__list_8h_source.html

like image 791
metdos Avatar asked Aug 23 '12 14:08

metdos


People also ask

Can you cast a null pointer?

You can cast null to any source type without preparing any exception. The println method does not throw the null pointer because it first checks whether the object is null or not. If null before it simply prints the string "null". Otherwise, it will call the toString purpose of that object.

Can I cast a void pointer to struct?

Yes, you then could use temp->value .

Can NULLptr be used in C?

At a very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are: a) To initialize a pointer variable when that pointer variable hasn't been assigned any valid memory address yet.


1 Answers

In assignment example the explicit cast make no useful sense. However, it seems that you the question is really about #define NIL ((List *) NULL) macro, whose usability extends beyond assignment.

One place where it might make sense is when you pass it to a variadic function or to a function declared without a prototype. The standard NULL can be defined as0 or 0L or ((void *) 0) or in some other way, meaning that it might be interpreted differently in such type-less contexts. An explicit cast will make sure that it is interpreted correctly as a pointer.

For example, this is generally invalid (behavior is undefined)

void foo();

int main() {
  foo(NULL);
}

void foo(List *p) {
  /* whatever */
}

while replacing the call with

foo(NIL);

makes it valid.

like image 151
AnT Avatar answered Oct 01 '22 21:10

AnT