如何将指向struct的指针设置为NULL

时间:2014-01-03 08:02:57

标签: 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

3 个答案:

答案 0 :(得分:2)

您希望更改(初始化)list指向的内容,以下是通常的做法:

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

答案 1 :(得分:2)

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

因此,即使您为其指定NULL,也会指向无效的内存。

但是listDocumentRowList_init的本地,所以它不会返回值,因为你只为它赋值,然后返回。

如果您想要返回DocumentRow的结构,则必须使用此

  *list = malloc( sizeof *L);

分配一个结构并将指针返回给它。

答案 2 :(得分:0)

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

请注意list =& L指定列表中位于变量上的变量的地址。所以一旦你存在函数,变量就超出了范围,你的列表就会指向某个位置(在堆栈上)。

相关问题