铸造NULL在C一个struct指针? [英] Casting NULL to a struct pointer in C?

查看:131
本文介绍了铸造NULL在C一个struct指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有铸造的NULL在C一个struct指针任何好处?

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

例如:

typedef struct List
{
....
} List;

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

这是PostgreSQL源代码示例:

Example from PostgreSQL source:

#define NIL                     ((List *) NULL)

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

推荐答案

在分配例子明确投不作任何有用的意义。然而,似乎你的问题实际上是关于的#define NIL((名单*)NULL)宏,它的实用性超出分配。

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.

一个地方,它可能是有意义的是,当你把它传递给一个可变参数函数,或者没有原型声明的函数。该标准 NULL 可以被定义为 0 0L ((无效*)0)或以其它方式,这意味着它可以是除$ p $在这种类型的无上下文PTED不同。显式类型转换将确保它是正确PTED为指针间$ P $。

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 */
}

在更换与呼叫

foo(NIL);

使得它有效。

这篇关于铸造NULL在C一个struct指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆