c - 在 void 指针中存储和打印字符串

标签 c pointers linked-list void-pointers

我编写了一个链表程序,它将数据成员存储为 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/

    相关文章:

    c++ - 如何将 vector 转换为数组并访问它

    c - 具有链表内存转储的结构

    java - 如何删除我在链接列表中选择的两个元素之间的所有元素

    c - 下面的文件写入代码有什么问题吗?

    c - 使用 fscanf() 读取一行

    C 告诉我初始化变量,即使它已经初始化

    c++ - 检查char *是否为null或为空时取消引用NULL指针警告

    谁能帮我解决这个结构/指针问题吗?

    c - 我应该声明作为函数参数传递的数组的预期大小吗?

    c - 如何在 C 中获取 lib 函数体?