我在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