小编ash*_*n71的帖子

在函数内分配内存后使用双指针

我正在玩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 …
Run Code Online (Sandbox Code Playgroud)

c pointers

1
推荐指数
1
解决办法
1218
查看次数

标签 统计

c ×1

pointers ×1