噫吁汐 2022-01-12 11:09 采纳率: 95%
浏览 56
已结题

c语言,输出链表有一处不懂


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct demo
{
    char str[15];
    struct damo* pnext;
};
struct demo* create()
{
    char str1[15];
    struct demo* pnew,*pend,*phead;
    pnew=pend=(struct demo*)malloc(sizeof(struct demo));
    phead=pnew;
    printf("请输入文字");
    gets(str1);
    strcpy(phead->str,str1);
    if(*str1)
    {
        for(;;)
        {
            pnew=(struct demo*)malloc(sizeof(struct demo));
            pend->pnext=pnew;
            printf("请输入文字");
            gets(str1);
            strcpy(pnew->str,str1); 
            if(!*str1)
            {
                break;
            }
            pend=pnew;
        }
    }
    pend->pnext=NULL;
    free(pnew);
    return phead;
}
void main()
{
    struct demo* phead;
    struct demo* pprint;
    phead=create();
    printf("\n输出为:\n");
    pprint=phead;
    puts(pprint->str);
    for(;;)
    {
        pprint=pprint->pnext;
        
        if(pprint==NULL)
        {
            break;
        }
        puts(pprint->str);
    }
    
}

上面是正确的版本,下面是错误的版本


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct demo
{
    char str[15];
    struct damo* pnext;
};
struct demo* create()
{
    char str1[15];
    struct demo* pnew,*pend,*phead;
    pnew=pend=(struct demo*)malloc(sizeof(struct demo));
    phead=pnew;
    printf("请输入文字");
        scanf("%s",*str1);
    strcpy(phead->str,str1);
    if(*str1)
    {
        for(;;)
        {
            pnew=(struct demo*)malloc(sizeof(struct demo));
            pend->pnext=pnew;
            printf("请输入文字");
            scanf("%s,str1);
            strcpy(pnew->str,str1); 
            if(!*str1)
            {
                break;
            }
            pend=pnew;
        }
    }
    pend->pnext=NULL;
    free(pnew);
    return phead;
}
void main()
{
    struct demo* phead;
    struct demo* pprint;
    phead=create();
    printf("\n输出为:\n");
    pprint=phead;
    printf("%s",*(pprint->str));
    for(;;)
    {
        pprint=pprint->pnext;
        
        if(pprint==NULL)
        {
            break;
        }
        printf("%s",*(pprint->str));
    }
    
}

这两个程序就有一个不同,就是正确的程序中用的是puts和gets,错误的程序中用的printf和scanf,我不太清楚为什么把printf和scanf换成puts和gets就正确了,求解答,谢谢

  • 写回答

4条回答 默认 最新

  • 关注

    我没有细看代码,但是你的代码本身就有问题,我主要看了这两个地方,其他有问题你自己找吧

    scanf("%s,str1);
    

    请改为

    scanf("%s",str1);
    

    然后

    printf("%s",*(pprint->str));
    

    请改为

    printf("%s",pprint->str);
    

    实际上,两种应该都可以,printf也应当调用指针

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 3月10日
  • 已采纳回答 3月2日
  • 创建了问题 1月12日

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助