我试图在一个函数中声明一个变量(结构类型),并从其他函数操纵它(读/写)。但是,当我尝试在未声明该变量的任何函数中使用该变量时,该变量仅包含垃圾。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
char name[25];
int roll;
float marks;
}Student;
void getInfo(Student student);
void display(Student student);
int main(int argc, char *argv[]) {
Student student;
getInfo(student);
display(student);
return 0;
}
void getInfo(Student student){
printf("Enter student's name: \n");
scanf("%s", &student.name);
printf("Enter student's roll: \n");
scanf("%d", &student.roll);
printf("Enter student's grade: \n");
scanf("%f", &student.marks);
}
void display(Student student){
printf("NAME: %s\n", student.name);
printf("ROLL: %d\n", student.roll);
printf("GRADE: %.2f\n", student.marks);
}
答案 0 :(得分:2)
您应该通过引用(&运算符)传递您的结构
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[25];
int roll;
float marks;
} Student;
void getInfo(Student *student);
void display(Student *student);
int main(int argc, char *argv[]) {
Student student;
getInfo( &student );
display( &student );
return 0;
}
void getInfo(Student *student){
printf("Enter student's name:");
scanf("%s", student->name);
printf("Enter student's roll:");
scanf("%d", &student->roll);
printf("Enter student's grade:");
scanf("%f", &student->marks);
}
void display(Student *student){
printf("NAME: %s\n", student->name);
printf("ROLL: %d\n", student->roll);
printf("GRADE: %.2f\n", student->marks);
}