【发布时间】:2019-06-15 00:44:45
【问题描述】:
我已经知道如何在 C 中将 int 添加到链表中,但我需要添加一个字符串,但它根本不起作用。
main函数从用户那里获取数据,加入链表后在show函数中打印出来。
列表和主要
struct nlista{
char dado[10];
struct nlista *prox;
}*Head;
int main(){
int op;
char data[10];
Head = NULL;
printf("type a value: ");
scanf("%s",&data);
inserir(data);
printf("the element is : ");
show();
}
inserir():在列表末尾添加元素
void inserir(char data){
nlista *novoelemento;
novoelemento = (struct nlista *)malloc(sizeof(struct nlista));
nlista *check;
check = (struct nlista *)malloc(sizeof(struct nlista));
novoelemento->dado = data;
if(Head == NULL){
Head = novoelemento;
Head->prox = NULL;
}
else{
check = Head;
while(check->prox != NULL)
check = check->prox;
check->prox = novoelemento;
novoelemento->prox = NULL;
}
show():显示链表
void show()
{
nlista *check;
check = (struct nlista *)malloc(sizeof(struct nlista));
check = Head;
if (check == NULL){
return;
}
while(check != NULL) {
printf("%s", check->dado);
check=check->prox;
}
printf("\n");
}
我错过了什么?编译器消息是:从 char* 到 char 的无效转换。在 inserir(data) 行中;
【问题讨论】:
-
为什么要在这一行新建一个元素:
check = (struct nlista *)malloc(sizeof(struct nlista));?新创建的元素有什么用途?如果inserir应该添加一个字符串,为什么它需要一个字符参数?让 cmets 解释为什么要按原样编写代码会有所帮助。 -
data衰减为指针 (char *) 但void inserir(char data)要求char -
@DavidSchwartz 检查将验证列表的实际元素是否为空。该应用程序是关于添加具有多种数据类型的链表,但我坚持添加字符串,所以我简化了代码。那么应该是什么样的参数呢?
-
@saulodev 可能是你想用什么来表示一个字符串。最常见的是
char*。 -
@davidschwartz 不能解决同样的问题
标签: c string data-structures linked-list