當我在單個函數中打開一個文件時,它會打開而不會出錯。如何在單獨的功能下打開文件進行閱讀而不會出現分段錯誤?
void fileOpen(char fileName[]){
FILE *file;
file = fopen(fileName, "r");
if(file != NULL) {
printf("Successfully opened.");
}
}
輸出:
Successfully opened.
然而,當我嘗試的過程中移動到一個單獨的函數,文件打開,但有段故障。
void fileOpen(FILE file, char fileName[]){
file = fopen(fileName, "r");
if(file != NULL) {
printf("Successfully opened.");
}
}
void fileStart(){
FILE *mainFile;
char name[] = "file.txt";
fileOpen(mainFile, name);
}
輸出:
Successfully opened.
segmentation fault (core dumped) ./executable
如果這是如何我傳遞變量請解釋錯誤。指針對我來說是一個弱點。
提示:爲什麼void void(int i){i = 5;} int main(){int x = 2; F(X); printf(「%d \ n」,x);返回0;}'不打印5? – immibis
坐下來冥想「**局部**變量」的意義(與「**全局**變量」相反)。 – Olaf