[英]Why does my output have garbage value, and how to fix it?
#include<stdio.h>
struct info {
char album[30];
int released;
char group[30];
};
int main() {
FILE * fpt;
int size;
struct info band[size];
int i;
printf("How many groups would you like to input: ");
scanf("%d",&size);
for (i=0; i<size; i++) {
printf ("Input what group: ");
scanf(" %s", band[i].group);
printf("Input released date: ");
scanf(" %d", &band[i].released);
printf("Input what album: ");
scanf(" %s", band[i].album);
}
fpt = fopen("records.dat", "w");
// printf("Group\t\tReleased\t\tAlbum\n");
for (i=0; i<size; i++) {
fprintf(fpt,"%s\t\t%d\t\t%s\n", band[i].group, band[i].released,
band[i].album);
}
printf("File created.\n");
fclose(fpt);
}
這是輸出:
ø -605554032 entropy // 但下一行輸出是正確的
您在此處遇到了對帶陣列的內存分配問題。 當您編寫“struct info band [size]”時,您實際上是在告訴您的計算機:“請為我創建大小結構並在堆棧中為它們找到一個位置”。 但是,由於兩個原因,這不能在這里發生:
正如我上面的評論所說,當該行發生時,變量大小未初始化。
即使你有這樣的代碼: size=3; struct info band[size]
size=3; struct info band[size]
事情不起作用,因為程序必須知道它應該在編譯時為堆棧上的帶數組創建多少空間,而在運行時設置大小變量 - 使用 malloc 來克服這個問題: scanf(%d, &size); struct info * band = (struct info*)malloc(sizeof(struct info) * size);
scanf(%d, &size); struct info * band = (struct info*)malloc(sizeof(struct info) * size);
這將為堆棧上的數組僅創建 4 個字節(即:指針大小),同時為堆上的實際數組動態分配相關內存。
在main函數的最后別忘了加上free(band);
祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.