繁体   English   中英

在c中传递char **时出现分段错误

[英]Segmentation fault when passing char** in 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]);
        }
    }
}

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

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

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

然后你的函数定义为:

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

你会取消引用strWordArray并分配给它:

*strWordArray = strInternalWordArray;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM