[英]printf isn't printing the right number
我有這個作為我的結構
struct theFile{
int count;
FILE *fPointer;
int *fileItems[];
}myFile;
這是將文件保存在fileItems中的方法。 它正在正確保存數字。 例如fileItems[0] = 5
, fileItems[1] = 45
, fileItems[2] = 35
void saveFile(){
myFile.fPointer = fopen("mileage.txt", "r");
int i = 0;
while (!feof(myFile.fPointer)){
myFile.fileItems[i] = (int*)malloc(sizeof(int));
fscanf(myFile.fPointer, " %d,", myFile.fileItems[i]);
i++;
}
myFile.count = i;
}
但是當我使用這種方法打印文件的內容時,它將正確打印第一個數字,然后將其余的打印為大數字。 有人可以告訴我為什么它不能打印數組的正確內容。
void viewFile(){
for(int i = 0; i < myFile.count; i++){
printf("%d, ", myFile.fileItems[i]);
}
}
還請注意,它是用c編寫的。
int *fileItems[];
等於int ** fileItems;
您最有可能需要一個整數數組,而不是一個指向整數的指針數組。
將結構聲明更改為int * fileItems;
,並在循環前分配一次列表:
myFile.fileItems = malloc(sizeof(int) * initialNumberOfElements);
以后,如果initialNumberOfElements
太小,那么realloc
更多的空間:
myFile.fileItems = realloc(myFile.fileItems, sizeof(int) * biggerElementCount);
然后, fscanf
參數必須為&myFile.fileItems[i]
。
如果分配功能失敗,請不要忘記添加錯誤處理代碼。 您使用的所有文件功能都一樣:所有I / O都會失敗。
fscanf
要求一個指針作為參數,但是它通常是現有int
的地址,而不是“真實” int*
。 您可能打算寫:
struct theFile{
int count;
FILE *fPointer;
int fileItems[N]; // You need to put a value as N, like 10, or else the array will be of size 0
}myFile;
然后
fscanf(myFile.fPointer, " %d,", &myFile.fileItems[i]); // with a & to get the address
這樣,您不需要malloc
和free
。 剩下的就沒事了。
編輯:如果您不知道您將事先擁有幾個int
,則user694733的答案會更好。
在結構中進行聲明。
struct theFile{
int count;
FILE *fPointer;
int *fileItems[MAX];// MAX=10;
}myFile;
空數組下標不知道數組如何指向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.