为什么我的输出给出垃圾值?

问题描述

我正在学习结构和功能,并且试图将指向结构的指针作为参数传递。我的代码是输入学生的姓名,年龄和分数。这是我的程序

  #include<stdio.h>
  #include<string.h>
  #include<stdlib.h>


 struct student {   
 char name[15];
 int age;
 double marks; 
 };

 void display(); 

 int main(){

 struct student *s1;

 s1 =(struct student *) malloc(sizeof(struct student));
 for(int i=0; i<2; i++)
 {
    printf("\nEnter details of student %d\n\n",i+1);

    printf("Enter name: ");
    scanf("%s",s1->name);

    printf("Enter age: ");
    scanf("%d",&s1->age);

    printf("Enter marks: ");
    scanf("%f",&s1->marks);
}
display(&s1);       
}

void display(struct student *s1){ 

printf("\nName\tAge\tMarks\n");

for(int i = 0; i<2;i++ )
 {
    printf("Name: %s",s1->name);
    printf("\nAge: %d",s1->age);
    printf("\nMarks: %.2lf",s1->marks);
 }
}

代码运行,但是给出了错误输出垃圾值。我做错了什么?

解决方法

有几种语法错误。我在下面的代码中包含了文档。

此外,每次提示用户输入时,都会覆盖s1的内容。例如,使用两个不同的数据(名称:“ alex”,年龄:19,标记:100.0和名称:“ jason”,年龄:22,标记:100.0)对其进行测试。您的程序只会稍后输出。

为解决这个问题,我建议您在循环之前分配学生指针,以便为每个学生有两个不同的内存,并且在这种情况下不会覆盖它们。

基本上,每个学生结构都被视为一个数组,而不是s1-> name,您将它们取消引用为s1 [i] .name

显示函数声明

void display(struct student *s1);

主要功能

int main()
{
    int i;
    struct student *s1;

    s1 =(struct student *) malloc(sizeof(struct student) * 2);  /* 2 = number of students */

    for(i=0; i<2; i++)
    {
        printf("\nEnter details of student %d\n\n",i+1);

        printf("Enter name: ");
        scanf("%s",s1[i].name);

        printf("Enter age: ");
        scanf("%d",&s1[i].age);

        printf("Enter marks: ");
        scanf("%lf",&s1[i].marks);   /* Instead of %f,it should be %lf */

    }

    display(s1);    /* Instead of &,it should be s1 */   

    /* Free heap memory */
    for(i=0; i<2; i++)
    {
        free(s1);
        s1 = NULL;
    }

    return 0;
}

显示功能,您还需要对显示功能进行一些修改

void display(struct student *s1)
{ 
    int i;
    printf("\nName\tAge\tMarks\n");

    for(i = 0; i<2;i++ )
    {
        printf("%s\t",s1[i].name);
        printf("%d\t",s1[i].age);
        printf("%.2f\t",s1[i].marks);  /* Instead of %.2lf,it should be %.2f */
        printf("\n");
    }
}

学生结构

struct student
{   
    char name[15];
    int age;
    double marks; 
};