[英]Segmentation Fault with string compare
當使用這樣的基本示例時,出現了分段錯誤。 我認為這是由於數據大小不固定所致。 如何將可變長度數據附加到結構上?
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;
}
How can I have variable length data attached to a struct?
答案是- 不 ,您不能。 原因是應該在編譯時知道該結構的大小。
分段錯誤的原因是,您的程序在分配內存之前正在訪問head
指針:
struct Node* head = NULL;
head->data = "abc";
在使用head
之前分配內存:
struct Node* head = NULL;
head = malloc (sizeof(struct Node));
if (NULL == head)
exit(EXIT_FAILURE);
head->data = "abc";
完成后,請確保釋放已分配的內存。
在C99標准中引入了一些稱為靈活陣列成員(FAM)的東西。 這可能是您的興趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.