大佬们 秋梨膏这个是什么原因导致输入无法成功保存输入内容的?

# include <stdio.h>
# include <malloc.h>

struct student{
    char name[100];
    int score; 
};

void inputstudent(struct student *, int);
void outputstudent(struct student *, int);
void sort(struct student *,int);

int main()
{
    struct student * st;
    int len,i;

    printf("请输入有几个学生");
    scanf("%d",&len);

    st = (struct student *)malloc(sizeof(struct student)*len);

    for (i=0; i<len; i++)
    inputstudent(st+i,i);

    sort(st,len);

    for (i=0; i<len; i++)
    {
        outputstudent(st+i,i);
    }

    return 0;
}

void inputstudent(struct student * qst, int n)
{
    printf("请输入学生名字 ");
    scanf("%s",&qst[n].name);

    printf("请输入该学生的成绩 ");
    scanf("%d",&qst[n].score);
}
void outputstudent(struct student * pst, int n)
{
    printf("名字:%s 成绩:%d\n",pst[n].name,pst[n].score);
}
void sort(struct student * p, int n)
{
    int i,j;
    struct student t;
    for (j=1; j<n; j++)
    {
        for (i=0; i<n; i++)
        {
            if (p[i].score<p[i+1].score)
            {
                t = p[i];
                p[i] = p[i+1];
                p[i+1] = t;
            }
        }
    }
}

应该是因为inputstudent()函数里面获取姓名字符串那里, 加了取址符;

然后调用inputstudent()函数时,第一个参数加了i这个偏移量,导致存储位置不对;

另外调用outputstudent()函数的第一个参数也不需要加i这个偏移量。

修改如下:

参考链接:



# include <stdio.h>
# include <malloc.h>
 
struct student{
    char name[100];
    int score; 
};
 
void inputstudent(struct student *, int);
void outputstudent(struct student *, int);
void sort(struct student *,int);
 
int main()
{
    struct student * st;
    int len,i;
 
    printf("请输入有几个学生");
    scanf("%d",&len);
 
    st = (struct student *)malloc(sizeof(struct student)*len);
 
    for (i=0; i<len; i++)
       // 函数第一个参数,传入结构数组首地址即可,因为加上第二个参数会找到指定的结构 
        inputstudent(st,i);
 
    sort(st,len);
 
    for (i=0; i<len; i++)
    {
        // 同上,函数第一个参数,传入结构数组首地址即可,因为加上第二个参数会找到指定的结构 
        outputstudent(st,i);  
    }
 
    return 0;
}
 
void inputstudent(struct student * qst, int n)
{
    printf("请输入学生名字 ");
    // 获取姓名字符串,不需要加取址符了,因为name是姓名字符数组地址 
    scanf("%s",qst[n].name);  
 
    printf("请输入该学生的成绩 ");
    scanf("%d",&qst[n].score);
}
void outputstudent(struct student * pst, int n)
{
    printf("名字:%s 成绩:%d\n",pst[n].name,pst[n].score);
}
void sort(struct student * p, int n)
{
    int i,j;
    struct student t;
    // https://www.runoob.com/w3cnote/bubble-sort.html
    // 冒泡排序这里修改下 
    for (j=0; j<n-1; j++)
    {
        for (i=0; i<n-1-j; i++)
        {
            if (p[i].score<p[i+1].score)
            {
                t = p[i];
                p[i] = p[i+1];
                p[i+1] = t;
            }
        }
    }
}


img