我正在處理一個打開文件的函數, 函數將該文件的內容讀入動態數組, 一個關閉文件的函數。在單獨的函數中創建一個動態數組,並從調用函數中對其進行操作
到目前爲止,我能夠做到以上所有,除了當我回到調用位置(main)時動態數組超出範圍。我想在主數據庫甚至單獨的函數中存儲數組中的附加數據。一旦我完成向動態數組添加數據,我將把它的內容寫回到源文件中,用新數據覆蓋它,然後關閉該文件。目的是將數據追加到原始文件的頂部。我在做什麼錯誤的功能char *LoadFileData(FILE *fp, char* charPtr);
,我無法訪問或修改它在主?
感謝您的幫助。
FILE *fSource; // create source file pointer instance
char mode[] = "a+"; // default file open mode
char inStr[80]; // string to get input from user
char *tempFileData; // dynamic string to hold the existing text file
// Open the source file
strcpy(mode, "r"); // change the file opnen mode to read
FileOpen(&fSource, mode);
// Load the source file into a dynamic array
LoadFileData(fSource, tempFileData); // this is where I fail that I can tell.
printf("%s", tempFileData); // print the contents of the (array) source file //(for testing right now)
FileClose(&fSource); // close the source file
Ĵ
char *LoadFileData(FILE *fp, char* charPtr)
{
int i = 0;
char ch = '\0';
charPtr = new char; // create dynamic array to hold the file contents
if(charPtr == NULL)
{
printf("Memory can't be allocated\n");
exit(0);
}
// loop to read the file contents into the array
while(ch != EOF)
{
ch = fgetc(fp); // read source file one char at a time
charPtr[i++] = ch;
}
printf("%s", charPtr); // so far so good.
return charPtr;
}
'charPtr = new char;'不會分配給你一個動態數組。改用'new char [length]'。 –
你的數組沒有超出範圍,你沒有把它的指針返回到你的調用函數。你的charPtr參數可以作爲char *&charPtr傳遞。或者像其他人所建議的那樣分配返回值。 –