c 中的数组链表
我在将数组分配为链接列表的元素时遇到问题。我尝试将 char 更改为 char* 但它对我没有帮助。我真的很感激你的名字 在这里我创建了一个结构
struct node{
char data;
struct node *next;
};
并添加了这个函数来添加新节点
void addLast(struct node **head, char val)
{
//create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
//if head is NULL, it is an empty list
if(*head == NULL)
*head = newNode;
//Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
//last node's next address will be NULL.
while(lastNode->next != NULL)
{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
,这就是如何将数据传递给函数
int main()
{
struct node *head = NULL;
char name[10];
printf("Enter book title : ");
scanf("%s",&name);
addLast(&head,name);
break;
return 0;
}
,这是我得到的错误
error: invalid conversion from 'char*' to 'char' [-fpermissive]
| addLast(&head,name);
| ^~~~
| |
| char*
note: initializing argument 2 of 'void addLast(node**, char)'
void addLast(struct node **head, char val)
i have problem with assigning an array as an element of a linked list. I've tried changing char to char* but it didn't help me. I would really appreciate your name
here i created a struct
struct node{
char data;
struct node *next;
};
and added this function to add new nodes
void addLast(struct node **head, char val)
{
//create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
//if head is NULL, it is an empty list
if(*head == NULL)
*head = newNode;
//Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
//last node's next address will be NULL.
while(lastNode->next != NULL)
{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
and this is how to pass the data to function
int main()
{
struct node *head = NULL;
char name[10];
printf("Enter book title : ");
scanf("%s",&name);
addLast(&head,name);
break;
return 0;
}
and this is the error i get
error: invalid conversion from 'char*' to 'char' [-fpermissive]
| addLast(&head,name);
| ^~~~
| |
| char*
note: initializing argument 2 of 'void addLast(node**, char)'
void addLast(struct node **head, char val)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需重新声明结构,
在这种情况下,函数将如下所示
Just redeclare the structure like
In this case the function will look like
为了存储书名,您需要为整个标题保留空间,而不仅仅是一个字母。
在读取名称时更改
为
现在,在新节点中为文本分配内存
一些其他观察结果
保留指向最后一个元素的指针,即使附加速度更快。
对于书名来说,10(9) 个字符的缓冲区可能有点小
In order to store the book title you need to reserve space for the whole title and not just one letter
Change
To
Now when reading the name, allocate memory in your new node for the text
Some other observations
Keep a pointer to the last element, that makes appending faster.
10(9) chars may be a bit small buffer for a book title