我编写了一个链表程序,它将数据成员存储为 void *。
在尝试使用 scanf/printf 函数存储和打印时,我遇到了段错误。
节点定义 -->
typedef struct node {
struct node *next;
void *data;
}node;
主函数 -->
head=(node *)malloc(sizeof(node));
if (head==NULL){
printf("error in allocation of memory\n");
exit(EXIT_FAILURE);
}
tail=(node*)create(head);
创建函数 -->
void *create(node *current)
{
int user_choice;
while(current){
printf("\nEnter the data:");
scanf("%s",current->data);
printf("stored at %p\n",(void*)current->data);
printf("%s",(char*)current->data);
printf("\nType '1' to continue, '0' to exit:\n");
scanf("%d",&user_choice);
if(user_choice == 1){
current->next=(node*)malloc(sizeof(node));
current=current->next;
}
else{
current->next=NULL;
}
}
return current;
}
谁能告诉scanf和prinf的正确论点应该是什么?
working code after incorporating points given in answers...
void *create(node *current)
{
node *temp;
int user_choice;
while(current){
printf("\nEnter the data:");
current->data=(char*)malloc(10*sizeof(char));
scanf("%s",current->data);
printf("stored at %p\n",(void*)current->data);
printf("%s",(char*)current->data);
printf("\nType '1' to continue, '0' to exit:\n");
scanf("%d",&user_choice);
if(user_choice == 1){
current->next=(node*)malloc(sizeof(node));
}
else{
current->next=NULL;
temp=current;
}
current=current->next;
}
return temp;
}
最佳答案
在您的代码中,
scanf("%s",current->data);
尝试使用未初始化的指针,它调用 undefined behavior .
您需要遵循以下任一方法,
malloc()
和 family 进行动态分配)关于c - 在 void 指针中存储和打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41018254/