我正在嘗試直接從 txt 檔案中動態分配單詞以供進一步使用,但在輸入檔案名后,程式崩潰并回傳負值(CodeBlocks)。這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define L 18
#define F 50
int main()
{
char **text = NULL;
int wcount=0;
text = textInput(&wcount);
free(text);
return 0;
}
char** textInput(int *wcount)
{
FILE *loadfile;
char fname[F];
char *word;
char **text;
printf("\nType the file of the name you would like to load: ");
scanf("Is", fname);
strcat(fname, ".txt");
if((loadfile = fopen(fname, "rt")) == NULL)
perror("Cannot open file");
while(fscanf(loadfile,"s", word = (char*)malloc(L*sizeof(char)))!= EOF)
{
(*wcount) ;
text = (char**)realloc(text, (*wcount)*sizeof(char *));
text[(*wcount)-1] = word;
}
fclose(loadfile);
free(word);
return text;
}
uj5u.com熱心網友回復:
在函式中,您在呼叫之前textInput還沒有初始化。在呼叫之前添加初始化。例如textrealloc(text, ...)text = NULLrealloc
char **text = NULL;
你已經有這樣的一行 in main(),但是 inmain()沒關系,變數textinmain()與變數textin不同textInput()。(此外,在 中main(),您text在嘗試使用它之前重新分配,因此不需要初始化textto 。)NULL
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473737.html
標籤:C
上一篇:char指標作為C中的函式引數
