![](/img/trans.png)
[英]How to fix my code to read a string in a function that returns a pointer to a struct
[英]How to fix my code to return a pointer to a struct from a function
我現在正在學習指針和結構,我有點困惑。 特別是,我想制作一個 function ,它返回一個指向結構的指針。 我的代碼正在編譯,但它不工作。 在我輸入學生人數后,它會詢問姓名和年齡(不讀姓名),在我輸入年齡后,它會關閉。
#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()
function 的堆棧上本地分配,但是這個 memory 一旦返回就不再為您保留。 這意味着您(充其量)得到垃圾。
您必須在function中分配 memory 並將其返回(並記住釋放它。)或將數據傳遞給 function 以填充它。
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);
...
}
我通常更喜歡在可能的情況下將數據傳遞給function,因為它簡化了 memory 管理。
編輯:關於您現有的details_pointer()
function 的兩個注釋。
1) 在fgets(pointer[i].name, 100, stdin)
中,如果已知數組的大小,最好從數組的大小中導出字節數; 在這種情況下,所以推薦fgets(pointer[i].name, sizeof(pointer[i].name), stdin)
。 您的並沒有錯,但是如果將來尺寸發生變化,維護起來會更容易。
2) scanf("%d", pointer[i].age)
需要獲取.age
的地址來填充它的值; 您傳遞的是數字而不是地址,這肯定是不正確的。
好的,所以如果分配需要動態分配,那么這就是我們必須做的。
僅指定一個數組會在 function 運行時隱式分配空間,但當 function 返回時它會消失。 您需要專門分配它。
重新訪問您的代碼:
struct details *details_pointer(int n)
{
struct details *students = (struct details *)malloc(n * sizeof(struct details));
.... do stuff with students[0] and the like
return students;
}
這使用malloc()
- memory allocate - library function 為您獲取一些空間,並且在您釋放它之前它一直有效。 字節數是你想要多少東西( n
)乘以一件東西的字節數( sizeof(struct details)
)
之后:
int main()
{
struct details *student = details_pointer(n);
.. do stuff
free(student);
}
現在使用memory,並在完成后將其釋放回操作系統。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.