[英]I'm making a linked list of strings in C, and having a problems
我是編程初學者。 謝謝你幫助我。
我正在嘗試在字符串中創建一個鏈接列表。 輸入是字符串,如果輸入是“退出”則結束。 但是當我編譯它時,它只打印出最后的輸入,我無法解決它,來自 function addrear。 它區分數據是否第一次存儲在鏈表中。 並適當地存儲數據和鏈接到另一個節點,來自 function 打印列表。 它從鏈表的開頭開始並打印出每個節點中的數據。
我已經用 integer 類型嘗試過,當這段代碼用 int 而不是 string 執行時,它工作正常,所以我認為錯誤來自字符數組。
例如)輸入1“轉儲”,
輸入2“結束”,
輸入3“目錄”,
輸入4“退出”,
比 output 會
轉儲,結束,目錄,退出
但它出來了
退出 退出 退出
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char instruction[1000];
struct Node {
struct Node* next;
char* data;
};
struct Node* pStart = NULL;
struct Node* pEnd = NULL;
void addrear(char* val)
{
struct Node* Current;
Current = (struct Node*)malloc(sizeof(struct Node));
Current->data = val;
Current->next = NULL;
//printf("%s\n", Current->data);
if (pStart == NULL)
{
pStart = Current;
pEnd = Current;
}
else
{
pEnd->next = Current;
pEnd = Current;
}
}
void printlist(struct Node* Current)
{
Current = pStart;
while (Current != NULL)
{
printf("%s\n", Current->data);
Current = Current->next;
}
}
int main()
{
int i;
while (1)
{
printf("sicsim> ");
fgets(instruction, sizeof(instruction), stdin);
instruction[strlen(instruction) - 1] = '\0';
addrear(instruction);
if (strcmp(instruction, "exit") == 0)
{
break;
}
}
printlist(pStart);
}
您的錯誤是您在 Node 結構中存儲了指向指令緩沖區的指針。 每次讀取字符串時,都會用讀取的字符串覆蓋該緩沖區。
您需要為每個字符串分配 memory。
如果您正在學習 C++,請查看有關“新”的文檔(您應該如何為 Node 分配空間等)
正如 MZB 回答的那樣,您的問題是您混淆了參考和價值。
你說:“我已經用integer類型試過了,當這段代碼用 int 而不是 string 執行時,它工作正常,所以我認為錯誤來自字符數組。”
分配int
的值和分配字符串之間存在巨大差異。 無論如何,你都會得到這個int
的價值——你不在乎他“住在哪里”。 當我們談論char
時也是如此,但是如果您談論字符串 - 您想指向這個字符串 - 所以您想要指向某個可以保存您的數據並且不會被修改的地方。
如果你想保存這個字符串,你需要知道字符串存儲的地方不會被訪問。
因此,您應該逐個字符地復制字符,這樣您就不會關心“指令”是否會被分配為其他內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.