【发布时间】:2014-09-10 15:31:31
【问题描述】:
我在 C 中使用双指针,想知道我是否创建了一个初始化表的函数,当我尝试使用 InitStringTable 分配的内存时,它在返回 main 时崩溃。我相信一个简单的解决方法是使 strTable 全局化,然后我相信它可以,但我不喜欢这样做,因为这对我来说更像是一个学习练习,我将表格传递给修改,即我应该能够修改 strTable 从initStringTable 之后的 main 或另一个函数 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中这样做)的事实之外,这与你应该使用std::string,std::vector而不是使用原始的C++有什么关系指针? -
看来您需要将
table = (char**)malloc(sizeof(char)*10);更改为table = (char**)malloc(sizeof(char*)*10);,因为table是char *的数组。 -
为什么你的函数是无效的?为什么不将返回值用于有用的东西?
-
间接疯狂...如果您希望
InitStringTable更改作为参数传递的变量,则必须将指针传递给该变量,即:&strTable,这意味着您必须将InitStringTable更改为char ***table。但实际上:三层间接不是你想要的 -
是的,这不应该是 C++。我的错。是的,我应该分配 char* 而不是 char。看起来我可以返回 char** 或接受 char*** 来解决我的问题。谢谢。