【发布时间】:2019-05-12 15:06:57
【问题描述】:
我正在尝试创建一个 包含 char 类型数据的链表。
由于某种原因,代码不起作用。 GCC 编译器对函数“add_bottom_ListEl”的警告是
“警告:传递 'add_bottom_listEl' 的参数 2 从指针生成整数而不进行强制转换”
和
"注意:预期为 'char',但参数类型为 'char *"
我怀疑我使用指针的方式有问题,但我尝试了很多很多组合,将指针传递给函数等......但似乎没有任何效果。
这里是 main 函数和所有其他函数。所有文件中都定义了 MAX_CHAR (#define MAX_CHAR 30)
int main()
{
char name[MAX_CHAR];
scanf("%s", name);
ListEl *head = malloc(sizeof(ListEl));
strcpy(head->name, name);
head->next = NULL;
printf("%s", head->name);
add_bottom_listEl(head, name);
print_listEl(head);
return 0;
}
void add_bottom_listEl (ListEl *head, char name)
{
ListEl *newEl;
while(head->next!=NULL)
{
head=head->next;
}
newEl = (ListEl*) malloc(sizeof(ListEl));
strcpy(newEl->name, name);
newEl->next = NULL;
}
void print_listEl(ListEl* head)
{
puts("print");
ListEl* current = head;
while (current!=NULL)
{
int i=1;
printf("%d.%s\n", i, current->name);
++i;
current = current -> next;
}
}
ListEl结构只是链表的一个常规元素
struct ListEl
{
char name[MAX_CHAR];
struct ListEl* next;
};
显然,我用过
typedef struct ListEl ListEl;
互联网或本网站上的每个链表教程都只展示了如何处理一般的整数或数字列表,而不是数组(字符)。有谁能帮帮我吗?
【问题讨论】:
-
void add_bottom_listEl (ListEl *head, char name)-name应该是char*。 -
还要确保你有在 main 之前声明的函数
-
它们在我的代码中分别声明在 .c 和 .h 文件中
-
在复制名称的函数中,使用 strncpy 传递 MAX_CHAR -1 作为最后一个参数,然后确保使用 [MAX_CHAR-1] = '\0'; 终止名称;
标签: c list pointers linked-list char