从函数内部更改结构

标签 c struct

我想将用户的学生详细信息打印到学生结构中,但我不明白为什么当我使用 Linux 终端进行编译时,没有条目或输出。请帮助我,我是新来的。

这是我的代码:

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

struct student 
{
char *name;               

int id;                   

char enroll;             

};

int main()
{
struct student john;
john.name = "John Smith";
john.id = 12345678;
john.enroll = 'D'; 

}

void getStudent(struct student *john)
{

printf("Type the name of the student: ");
john->name = malloc(100);   

fgets(john->name, 100, stdin);

printf("\nType the student number: ");
scanf("%d", &(john->id));

printf("\nType the student enrollment option (D or X): ");
scanf("%c", &(john->enroll)); 
return;
}

void printstudent(struct student john)
{

printf("Student name: %s\n", john.name);

printf("Student number: %d\n", john.id);

printf("Student enrollment option: %c\n", john.enroll);

return;

}

最佳答案

您需要从 main (或任何需要它们的函数)调用您的函数。编写函数(声明它)实际上并不执行它。

int main()
{
    foo();   // execute foo (call it)
}

void foo()
{
    // do stuff
}

您的函数是类似 printf() 和 scanf() 的函数,也必须调用才能使用。

关于从函数内部更改结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388442/

相关文章:

在两个结构指针之间复制数据会出现段错误

c - 使用用户输入填充结构并通过指针访问

c - 文件读写C

我的结构中声明的变量可以有不同的大小吗

c - 结构数组使用 malloc 时大小错误

c - 指针在 C 中给我垃圾,尽管在另一个函数中是正确的

c - 如何用C画一个椭圆?

c - 查找任意树 C 中的节点

c - c语言中的%d和%*d有什么区别?

arrays - 如何将结构保存到 Realm ,并包含另一个结构的列表