[英]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.