我现在正在学习指针和结构,我有点困惑。特别是,我想创建一个返回指向结构的指针的函数。我的代码正在编译,但它不工作。在我输入学生人数后,它会询问姓名和年龄(不读姓名),在我输入年龄后,它会关闭。
#include <stdio.h>
#include <stdlib.h>
struct details
{
char name[100];
int age;
};
struct details * details_pointer(int n)
{
struct details pointer_x[n];
struct details *pointer = pointer_x;
for (int i=0; i<n; i++)
{
printf("Student %d:\n", i);
printf("name:\n");
fgets(pointer[i].name, 100, stdin);
printf("age:\n");
scanf("%d", pointer[i]. age);
}
return pointer;
}
int main()
{
int n;
printf("Type the number of persons:\n");
scanf("%d", &n);
struct details *student = details_pointer(n);
printf("\nName: %s\n", (*student).name);
printf("Age: %d\n", (*student).age);
system("pause");
return 0;
}
最佳答案
这里的问题是您要返回一个结构变量 (pointer_x
),它是在内部 details_pointer()
函数的堆栈上本地分配的,但是这个内存是返回后不再为您保留。这意味着你得到(充其量)垃圾。
您必须要么在函数中分配内存并返回它(并记住释放它!),要么将数据传递给函数以填充它。
void get_details(int n, struct details p[n])
{
for (int i = 0; i < n; i++)
{
// do stuff with p[i]
}
}
int main()
{
...
scanf("%d", &n);
struct details students[n];
get_details(n, students);
printf("\nName: %s\n", students[0].name);
...
}
我通常更喜欢尽可能将数据传递给函数,因为它简化了内存管理。
编辑:关于您现有的 details_pointer()
函数的两个注释。
1) 在 fgets(pointer[i].name, 100, stdin)
中,如果知道数组的大小,最好从中推导出字节数;在这种情况下是这样,所以建议使用 fgets(pointer[i].name, sizeof(pointer[i].name), stdin)
。你的没有错,但如果将来尺寸发生变化,维护起来会更容易。
2) scanf("%d", pointer[i].age)
需要取 .age
的地址在那里填充它的值(value);您传递的是数字而不是地址,这肯定是不正确的。
关于c - 如何修复我的代码以从函数返回指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684325/