Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用字符串比较的分段错误_C_Struct_Segmentation Fault - Fatal编程技术网

C 使用字符串比较的分段错误

C 使用字符串比较的分段错误,c,struct,segmentation-fault,C,Struct,Segmentation Fault,当处理这样一个基本示例时,我遇到了一个分段错误。我相信这是因为数据的大小没有固定下来。如何将可变长度数据附加到结构 struct Node { char * data; struct Node* next; }; void compareWord(struct Node** head_ref, char * new_data) { if (strcmp((*head_ref)->data, new_data) > 0) { head_ref->

当处理这样一个基本示例时,我遇到了一个分段错误。我相信这是因为数据的大小没有固定下来。如何将可变长度数据附加到结构

struct Node {
    char * data;
    struct Node* next;
};

void compareWord(struct Node** head_ref, char * new_data) {
  if (strcmp((*head_ref)->data, new_data) > 0) {
      head_ref->data = new_data;
  }
}

int main(int argc, char* argv[]) {
  struct Node* head = NULL;
  head->data = "abc";
  char buf[] = "hello";
  compareWord(&head, buf);
  return 0;
}
如何将可变长度数据附加到结构?

答案是-,你不能。原因是在编译时应该知道结构的大小

分段错误的原因是,您的程序在分配内存之前正在访问
指针:

  struct Node* head = NULL;
  head->data = "abc";
在使用
头之前分配内存

  struct Node* head = NULL;
  head = malloc (sizeof(struct Node));
  if (NULL == head)
      exit(EXIT_FAILURE);
  head->data = "abc";
确保用完分配的内存后释放它



C99标准中引入了一种称为。这可能是您感兴趣的。

如果您没有显示printWord功能,请在尝试使用它之前,将大量内存分配给
头部??(提示,它是一个初始化为
NULL
…的指针,如果您在为其分配内存之前尝试并使用它,则保证为segfault)@OldProgrammer-typo-fixed