c - 如何将指向结构的指针设置为 NULL

标签 c pointers struct initialization

typedef struct _DocumentRow
{
    char * code /** The code */;
    char * designation /** The designation */;
    double quantity /** The quantity */;
    char * unity /** The unity */;
    double basePrice /** The base price */;
    double sellingPrice /** The selling price */;
    double discount /** The discount */;
    double rateOfVAT /** The rate of VAT */;
    struct _DocumentRow * next /** The pointer to the next row */;
} DocumentRow;

void DocumentRowList_init(DocumentRow ** list) {
    DocumentRow *L;
    list = ( DocumentRow ** ) malloc( sizeof( DocumentRow* ) );
    if ( list == NULL ) {
        fatalError( "memory is not enough" );
    }
    L = NULL;
    list = &L;
}

在使用函数 DocumentRowList_init 后,当我测试 if ( *list == NULL ) 时,它的计算结果为 false,为什么?我已经设置了 list = &LL = NULL

最佳答案

你会在这里有未定义的行为。 L 是局部变量,因此当您通过指针指针返回它的地址时,该变量在 DocumentRowList_init 返回时不再存在。

因此,即使您将 NULL 分配给它,它也会指向无效内存。

但是 listDocumentRowList_init 的局部变量,因此它无论如何都不会返回值,因为您只是为其分配一个值然后返回。

如果你想返回 DocumentRow 的结构,你必须使用这个

  *list = malloc( sizeof *L);

分配一个结构并返回指向它的指针。

关于c - 如何将指向结构的指针设置为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899158/

相关文章:

c++ - 在 GCC 中欺骗预处理器 VARIADIC MACROS

c - 如何中断选择

c - 如何打印另一个进程的信息?

iphone - 使用我自己的 typedef 枚举,得到 'Makes pointer from integer without cast'

c++ - 有没有办法在 .cpp 中初始化/调用 CTOR?

arrays - 如何创建字典数组?

c - malloc 显示红线

pointers - 访问结构字段时 Golang 结构文字和指针之间的区别

C 错误解引用指向不完整类型链表 dic 的指针

结构 vector 的 C++ 初始化