简体   繁体   English

C结构的属性的默认值

[英]Default values for properties of C Struct

I'm trying to implement a push function for a linked list, but the following program is causing a segmentation fault. 我正在尝试为链表实现推送功能,但是以下程序导致分段错误。 I'm wondering a couple of things: what's the default value for properties of a struct? 我在想两件事:结构属性的默认值是多少? It seems that I have to manually set the value of head->next to be NULL . 看来我必须手动将head->next的值设置为NULL What is the default value of head->next then? 那么head->next的默认值是什么?

I believe the reason the program breaks is because in the push function, head->next != NULL so it then executes the line head = head->next , which leads me to wonder what the value of head->next is if it isn't NULL , and why this causes a segmentation fault? 我相信程序中断的原因是因为在push函数中, head->next != NULL因此它执行了head = head->next ,这使我想知道head->next的值是多少不是NULL ,为什么这会导致分段错误?

typedef struct Node {
    struct Node *next;
    int data;
} Node;

void push(Node *head, int data);

int main()
{
    struct Node *head = malloc(sizeof(Node));
    head->data = 1;

    // Works when I uncomment this line
    // head->next = NULL;

    push(head, 2);
    return 0;
}

/* Insert */
void push(Node *head, int data) {
    while (head != NULL) {
        if (head->next == NULL) {
            Node *n = malloc(sizeof(Node));
            n->data = data;
            head->next = n;
            break;
        }
        head = head->next;
    }
}

what's the default value for properties of a struct? 结构属性的默认值是多少?

C standard refers to struct fields as members , not properties . C标准将struct字段称为成员 ,而不是属性

Members of struct s in C have defined values in three situations: C中struct的成员在以下三种情况下定义了值:

  • When you allocate struct s in static/global memory, or 在静态/全局内存中分配struct ,或者
  • When you supply member values through an initializer, or 通过初始化器提供成员值时,或
  • You use memory allocation routine that zeroes out the memory. 您使用内存分配例程将内存清零。

In all other cases struct members must be assigned before the first use; 在所有其他情况下,必须在首次使用之前分配 struct成员。 reading them before assignment is undefined behavior. 在分配之前阅读它们是未定义的行为。

In your situation, struct is allocated in dynamic memory by malloc . 在您的情况下, struct是通过malloc在动态内存中分配的。 This means that its members must be assigned explicitly. 这意味着必须显式分配其成员。

If you switch to calloc from malloc , struct 's memory would be zeroed out for you: 如果从malloc切换到callocstruct的内存将为您清零:

Node *n = calloc(1, sizeof(Node));

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

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