第一次来这里,请保持温柔。
我试图将在函数中动态分配的字符串数组传递回主函数。当我尝试从根本上访问它时,出现分段错误。
我试图包括相关的代码,而我不希望它们是不相关的部分。
主要调用函数“readFileToWordsArray”。
“readFileToWordsArray”调用函数“convertWordListToArray”。
我不明白为什么,但是很高兴让我将char **(动态分配的字符串数组)从“convertWordListToArray”传递到“readFileToWordsArray”,我可以按您的期望进行访问。但是,当我尝试将其进一步传递回main并尝试在那里访问它时,出现了分段错误。即使我只是用以下内容读取了第一个元素(在其他功能中也能正常工作):
printf("Word read from array is : \"%s\"\n", strInputFileWords[0]);
谢谢!!!!
void convertWordListToArray(char **WordArray, StringNodePtr currentPtr)
{
...
while ( currentPtr != NULL ) /* while not the end of the list */
{
WordArray[intWordCounter]= malloc(strlen(currentPtr->strWord) + 1);
strcpy(WordArray[intWordCounter], currentPtr->strWord);
}
}
bool readFileToWordsArray( char **strWordArray, char *strWordFile, int *intWordArrayCount)
{
char **strInternalWordArray;
...
strInternalWordArray=malloc(intWordCounter * sizeof(char*) );
convertWordListToArray(strInternalWordArray, startPtr);
printf("Word read from array strInternalWordArray is : \"%s\"\n", strInternalWordArray[0]);
strWordArray = strInternalWordArray;
}
int main ( int argc, char *argv[] )
{
char **strInputFileWords;
...
if (readFileToWordsArray(strInputFileWords, strInputFile, &intInputFileWordsCount))
{
printf("words loaded correctly. count is %d\n\n", intInputFileWordsCount);
for (i=0;i<intInputFileWordsCount;i++)
{
printf("Word read from array is : \"%s\"\n", strInputFileWords[0]);
}
}
}
最佳答案
在readFileToWordsArray
中,您要为strWordArray
分配一个值,这是函数的参数。因此,对此变量的更改对调用函数不可见。
如果要在strInputFileWords
中修改main中的readFileToWordsArray
,则需要传递其地址:
if (readFileToWordsArray(&strInputFileWords, strInputFile, &intInputFileWordsCount))
然后,您的函数将定义为:
bool readFileToWordsArray( char ***strWordArray, char *strWordFile, int *intWordArrayCount)
然后您将取消引用
strWordArray
并分配给它:*strWordArray = strInternalWordArray;