我通过char ** input
来自 main()
至processInExp()
函数,然后我再次从 processInExp()
传递它函数到 getInput()
函数在读取文件时动态分配它。
内部 getInput()
功能 input
检查时已正确分配内存,但在 in processInExp()
中使用它时它遇到运行时错误。可能是什么问题?
下面是我的代码:
int getInput(char ** input, const char * fileName)
{
int numInput = 0;
int i, j;
char c;
char tempInput[100];
FILE * pFile;
if((pFile = fopen(fileName, "r")) == NULL)
{
printf("Cannot read file %s\n", fileName);
system("PAUSE");
exit(1);
}
while(!feof(pFile))
{
c = fgetc(pFile);
if(c == '\n') ++numInput;
}
/* printf("%d\n", numInput); */
input = (char**)malloc(numInput * sizeof(char*)); /* #2 MALLOC input */
rewind(pFile);
for(i = 0; !feof(pFile); ++i)
{
fscanf(pFile, "%[^\n]%*c", tempInput);
/* printf("%s\n", tempInput); */
input[i] = (char*)malloc((strlen(tempInput) + 1) * sizeof(char)); /* #3 MALLOC input[] */
strcpy(input[i], tempInput);
/* printf("%s\n", input[i]); */ /* #4 PRINT OUT PERFECTLY */
memset(tempInput, 0, sizeof(tempInput));
}
fclose(pFile);
return numInput;
}
void processInExp(char ** input, char ** output, const char * fileName)
{
int numFormula;
int i;
numFormula = getInput(input, fileName); /* #1 PASSING input */
/* printf("%s\n", input[0]); */ /* #5 RUNTIME ERROR */
output = (char**)malloc(numFormula * sizeof(char*));
system("PAUSE");
for(i = 0; i < numFormula; ++i)
{
convertIntoPost(input[i], output[i]);
printf("%d. %s -> %s", (i + 1), input[i], output[i]);
}
}
最佳答案
C
使用按值传递函数参数传递。所以,从函数内部 getInput()
,您无法更改变量 input
并期望该更改反射(reflect)在传递给函数的实际参数中。为此,您需要传递一个指向变量的指针,就像在这种情况下,您需要这样做
int getInput(char *** input, const char * fileName) { //notice the extra *
并且需要像这样称呼它
char ** inp = NULL;
getInput(&inp, ..........);
然后,
getInput()
将能够将内存分配给 *input
函数内部将反射(reflect)到 inp
.否则,从
getInput()
返回后,实际参数仍将未初始化并进一步使用(在您的情况下,在 for
函数中的 processInExp()
循环中)将导致 undefined behaviour .也就是说,还有两件重要的事情需要注意,
malloc()
的返回值和家人在C
. while ( !feof (file) )
always wrong? 关于c - 使用 malloc 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470053/