我在C中使用雙指針,並想知道如果我創建了一個初始化表的函數,當我嘗試使用分配給內存的內存時,它在返回主時崩潰InitStringTable。我相信一個簡單的解決方法是使strTable成爲全局的,然後我相信它是可以的,但是我不想這樣做,因爲這對我來說更像是一個學習練習,用於修改表格,即我應該能夠從InitStringTable之後的主要或另一個函數modifyTable。 感謝您提供任何幫助。在函數內部分配內存後使用雙指針
int main()
{
char** strTable;
// Allocates memory for string table.
InitStringTable(strTable);
// Below lines should be able to copy strings into newly allocated table.
// Below lines cause crash however.
strcpy(strTable[0], "abcdef");
strcpy(strTable[1], "xy");
}
// Allocates memory for the string table. This function should create a table
// of size 10 strings with each string 50 chars long. The code compiles fine.
void InitStringTable(char** table)
{
int i = 0;
table = (char**)malloc(sizeof(char)*10);
for(i = 0; i < 10; i++)
{
table[i] = (char*)malloc(sizeof(char)*50);
}
for(i = 0; i < 10; i++)
{
memset(table[i], 0, 50);
}
strcpy(table[0], "string1");
}
除了你投'malloc'(你不應該用C做)的事實,這是怎麼與C++相關,你應該使用'std :: string','std :: vector',而不是使用原始指針? – crashmstr 2014-09-10 15:33:28
看起來你需要改變'table =(char **)malloc(sizeof(char)* 10);'to'table =(char **)malloc(sizeof(char *)* 10);'因爲'table'是一個'char *'的數組。 – abiessu 2014-09-10 15:33:58
爲什麼你的函數無效?爲什麼不把返回值用於有用的東西? – wildplasser 2014-09-10 15:47:33