【发布时间】:2015-01-12 09:00:21
【问题描述】:
我想在 C 中创建一个链接列表,用户可以在其中输入字符串,这些字符串将作为节点存储在列表中。这是我的节点结构:
typdef struct NODE {
char word[50];
struct NODE* next;
} node;
从我的主要方法中,我想提示用户输入一个字符串,然后调用一个将字符串添加到链表的方法(但不包括空格后面的任何字符),并重复执行此操作直到用户输入一个终止进程的特定字符串,所以在我的主要方法中我有:
void main(){
node* fullList = NULL;
char stopString[5];
sprintf(stopString, "stop");
char string[50];
printf("Enter a word: ");
scanf("%[^ ]s", string);
while (strcmp(string, stopString) != 0) {
addToLinkedList(fullList, string);
printf("Enter a word: ");
scanf("%[^ ]s", string);
}
}
这是我的加法:
void addToLinkedList(node* list, char str[]) {
node* freeSpot;
node* newNode;
freeSpot = list;
if (list == NULL){
freeSpot = freeSpot->next;
}
newNode = (node *)malloc(sizeof(node));
newNode->word = str;
//strcpy(nweNode->next, str);
newNode->next = NULL;
freeSpot->next = newNode;
}
但我得到一个错误:
"incompatible types when assigning to type âchar[256]â from type âchar *â"
如果我替换“newNode->word = str;”使用下面注释掉的代码,我得到:
warning: passing argument 1 of âstrcpyâ from incompatible pointer type [enabled by default]
/usr/include/string.h:128:14: note: expected âchar * __restrict__â but argument is of type
âstruct NODE *â
我在这一点上很困,我不确定如何成功地实现它;有什么建议吗?
【问题讨论】:
-
和
if (list == NULL){-->while(freeSpot->next != NULL){ -
对于scanf,您不需要额外的
s,这很好scanf("%s", string);%s在读取空格字符后停止读取。另请注意,由于您没有为字符串输入分配新内存,因此列表中的所有字符串都将包含相同的值 -
void addToLinkedList(node* list, char str[]) {-->void addToLinkedList(node** list, char str[]) { -
和
if(*list == NULL) { *list = newNode;}
标签: c string dynamic linked-list arrays