繁体   English   中英

如何为结构体的指针分配null?

[英]How to assign null to pointer of struct?

我不确定我是否足够明确和明确。 但是,我不敢怀疑。 我正在尝试为指针分配一个NULL值。

给定代码:

typedef struct Date
{
int year;
int month;
}Date;

typedef struct Record
{
    char name[20];
    char cdate[20];
    float quanitity;
    int barcode;
    Date date;
}Record;

然后在主要:

Record *records = malloc(10 * sizeof(Record));
records[0] = NULL;

当我定义类似类型的数组时,这是行不通的,例如int我可以分配值,或者NULL例如

int *avi = malloc(sizeof(int)*10);
avi[0] = 3;
avi [0] = NULL;

它工作正常,我已经打印了值并看到了更改。 但是,当我对结构的指针数组执行相同的操作时,如上面所定义的,我只是不能分配NULL值。

毫无章法。 我正在使用Eclipse IDE。 提前致谢。

您的问题是records是指向10个对象的指针。 因此, records[0]是第一个对象。 您不能将对象设置为NULL

它仅适用于int因为将int设置为零,而不是NULL

NULL是一个内置常量,其值为0。这就是为什么您可以将其分配给基本类型(例如int和char)的原因。 由于使用C语言的特定结构,该函数适用于指针,该结构告诉编译器“ 0”表示“指向无效的内存地址”,该地址可能不是实际值“ 0”。

您无法将NULL分配给结构类型,因为您无法将结构设置为整数类型。

这是创建指向Record结构的指针数组的示例。 因为数组包含指向Record结构的指针,而不是直接包含Record结构,所以可以将指针设置为NULL-如果数组直接包含Record结构,则无法执行此操作。

#include <stdlib.h>

typedef struct Date
{
    int year;
    int month;
}Date;

typedef struct Record
{
    char name[20];
    char cdate[20];
    float quanitity;
    int barcode;
    Date date;
}Record;

int main()
{
    // We start by creating an array of 10 Record pointers.
    // records is a pointer to the array we create
    Record **records = malloc(10 * sizeof(Record*));
    // First thing is first - did it work?
    // There is no point in doing anything else if the array didn't get created
    if (records != NULL) {
        // The Record pointers are uninitialized
        // Arrays don't do that automatically
        // So we need to initialize all the pointers
        // in this case we set them all to NULL
        for (int i=0;i<10;i++)
            records[i] = NULL;
        // Later on in the program we might want to
        // create one Record structure and assign it to records[5]
        records[5] = malloc(sizeof(Record));
        // Again, we need to check if the Record structure got created
        if (records[5] != NULL) {
            // Do something with this Record structure
            // Fill it in, print it out, etc.
        }
        // Then at the end of the program
        // we want to deallocate all the Record structures we created
        for (int i=0;i<10;i++)
            if (records[i] != NULL)
                free(records[i]);
        // And finally we need to deallocate the array of pointers
        free(records);
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM