在我正在编写的程序中,我需要一个链接列表,所以它是一个非常具体的实现。它需要:
数据是一个cstring,长度不超过20个字符。我对C不太熟悉,下面的签名void addToEnd(llist root, char entery[51])会出现错误。我尝试用llist替换node,但是错误是“未知类型名称节点”。我怎么才能摆脱这个?
这是密码
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct node
{
char entery[51];
struct node* next;
} llist;
/*may be losing root address permanently*/
void addToEnd(llist root, char entery[51])
{
while(root->next != NULL)
root = root->next;
node last = malloc(sizeof(struct node));
root->next = last;
strcpy(last, entery);
}
int main()
{
struct node *root = malloc(sizeof(struct node));
root->next = NULL;
strcpy(root->entery, "Hello");
struct node *conductor = root;//points to a node while traversing the list
if(conductor != 0)
while(conductor->next != 0)
conductor = conductor->next;
/* Creates a node at the end of the list */
conductor->next = malloc(sizeof(struct node));
conductor = conductor->next;
if (conductor == NULL)
{
printf( "Out of memory" );
return EXIT_SUCCESS;
}
/* initialize the new memory */
conductor->next = NULL;
strcpy(conductor->entery, " world\n");
addToEnd(root, " at the");
addToEnd(root, " end");
/*print everything in list*/
conductor = root;
if(conductor != NULL)
{
while(conductor->next != NULL)
{
printf("%s", conductor->entery);
conductor = conductor->next;
}
printf("%s", conductor->entery);
}
return EXIT_SUCCESS;
}我不清楚的一点是,在我看到的所有例子中,它们都是typedef the struct。为什么?让我详细说明:如何知道您想要传递的只是node还是struct node。另外,我不太明白这一点,struct node的长度并不比一个类型的人的名字长多少。
发布于 2013-09-29 05:06:37
问题:
void addToEnd(llist root, char entery[51])应为void addToEnd(llist *root, char entery[51])。在这里,根必须是指针类型,否则实际上不能在函数中修改它的值并使它在函数之外可见。node last = malloc(sizeof(struct node));应为struct node *last = malloc(sizeof(struct node));。因为在C中,您必须使用关键字struct引用类型名称,而且它应该是一个指针,否则不能用malloc初始化它。至于你的typedef问题,我认为它是可选的,人们使用它只是为了方便。就我个人而言,我并不经常在typedef上使用struct。
编辑:
此外,您的代码还带有bug。抱歉,我之前只专注于语法。
请注意,C中的malloc并不能保证您对分配的内存很感兴趣,它实际上可能是内部的任何东西。因此,您需要手动填充它:在last->next = NULL;的末尾添加一行addToEnd。
发布于 2013-09-29 05:08:32
要引用链接列表的struct,请使用struct node,在typedef之后也可以使用llist。您也可以使用,如链接的问题使用。
typedef struct node
{
char entery[51];
struct node* next;
} node;在这种风格中,您可以使用与node相同的struct node。
您面临的语法错误是,您误用了箭头操作符->,它与指针 of struct一起使用。对于struct,使用点运算符.
所以对于这个函数
void addToEnd(llist root, char entery[51])
{
while(root->next != NULL)
root = root->next;您应该传入一个指针:
void addToEnd(llist* root, char entery[51])https://stackoverflow.com/questions/19074590
复制相似问题