【发布时间】:2011-11-28 20:41:57
【问题描述】:
我有一个包含字符串的节点链接列表。程序从 stdin 读取字符,直到它到达一个新行,一旦它把这个字符串放入列表的一个新节点。
我已经对程序中涉及的不同步骤进行了一些调试,并且可以看到正在正确创建的节点列表。
但是,如果我单步执行代码,printf 语句似乎没有任何作用。如果我不单步执行并运行代码,我会得到:
无法访问地址 0x2e666564 处的内存
无法访问地址 0x2e666564 处的内存
无法访问地址 0x2e666564 处的内存
我的源代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *string;
struct Node *next;
} List;
List *addNode(List *currentList, char *character)
{
List *tempList = calloc(1, sizeof(List));
tempList->string = strdup(character);
tempList->next = currentList;
return tempList;
}
void printList(List *currentList)
{
while (currentList != NULL)
{
printf("%s", currentList->string);
currentList = currentList->next;
}
}
int main ()
{
char currentCharacter;
char *currentString;
List *mainList = NULL;
do
{
currentCharacter = getchar();
if (currentCharacter == '\n')
{
mainList = addNode(mainList, currentString);
currentString[0] = '\0';
} else {
strcat(currentString, ¤tCharacter);
}
} while (currentCharacter != '.');
mainList = addNode(mainList, currentString);
printList(mainList);
return 0;
}
【问题讨论】:
标签: c linked-list