简体   繁体   中英

Segmentation fault when passing char** in c

first timer here, please be gentle.

I'm attempting to pass an array of strings that's been dynamically allocated within a function back to the main. When I attempt to access it in the main, I'm getting a segmentation fault.

I've tried to include the relevant code without what I'm hoping is the irrelevant parts.

Main calls the function "readFileToWordsArray". "readFileToWordsArray" calls the function "convertWordListToArray".

I don't understand why, but it'll happily let me pass my char** (dynamically allocated array of strings) from "convertWordListToArray" to "readFileToWordsArray" and I can access it as you'd expect. However, when I attempt to pass it further back to main, and try to access it there, I get a segmentation fault. Even if I just read the first element (which works fine in the other functions) with:

printf("Word read from array is : \"%s\"\n", strInputFileWords[0]);

Thanks!!!!

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]);
        }
    }
}

In readFileToWordsArray , you're assigning a value to strWordArray , which is a parameter to a function. Therefore, changes to this variable are not visible to the calling function.

If you want strInputFileWords in main to be modified in readFileToWordsArray , you need to pass its address:

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

Then your function would be defined as:

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

And you would dereference strWordArray and assign to that:

*strWordArray = strInternalWordArray;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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