在c

时间:2015-09-11 17:57:33

标签: c

这里的第一个计时器,请温柔。

我正在尝试将一个在函数内动态分配的字符串数组传递回main。当我尝试在主要访问它时,我遇到了分段错误。

我试图将相关代码包含在内,而不是我希望的那些无关紧要的部分。

Main调用函数“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]);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

readFileToWordsArray中,您要为strWordArray分配一个值,该值是函数的参数。因此,调用函数看不到对此变量的更改。

如果您希望在strInputFileWords中修改main中的readFileToWordsArray,则需要传递其地址:

if (readFileToWordsArray(&strInputFileWords, strInputFile, &intInputFileWordsCount))

然后你的函数定义为:

bool readFileToWordsArray( char ***strWordArray, char *strWordFile, int *intWordArrayCount)

你会取消引用strWordArray并指定:

*strWordArray = strInternalWordArray;