如何在C中初始化指向指针的指针

所以我得到了这个包含2个字段的struct NodeDataP datavoid * keyDataP只是void*typedef

我创建了一个双指针Node **table ,使其像2D数组一样。

我无法想象如何malloc它,我希望这个双指针充当2D数组,其中2为行数,x为cols数。

我试过table = (Node**)malloc(sizeof(Node*)*2); 但这是对的吗? 我该如何从这里继续?

我试过table = (Node**)malloc(sizeof(Node*)*2); 但这是对的吗?

是的,你正在以正确的方式做到这一点。 现在你有两个Node*类型的变量,它们是table[0]table[1]

请注意,您无需malloc()的返回值。 原因如下: 点击

我该如何从这里继续?

现在使用for循环为上述两个变量分配内存

 for(int index = 0; index < num_of_rows; index++) { table[index] = malloc(no_of_columns * sizeof(Node)); //don't cast the return value of malloc() } 

所以下次你想为双指针分配内存时,你可以这样做:

 table = malloc(no_of_rows * sizeof(Node)); for(int index = 0; index < num_of_rows; index++) { table[index] = malloc(no_of_columns * sizeof(Node)); } //Don't forget to free() the pointers you malloced when you no longer need them for(int index = 0; index < num_of_rows; index++) { free(table[index]); } free(table); 

大小为ROW_NUM x COL_NUM的表的分配内存顺序应如下:

1)指针数组的内存:

  Node ** table = malloc( sizeof(Node*) * ROW_NUM); 

2)每行的内存(需要循环)

  for(int i = 0; i < ROW_NUM; i++) table[i] = malloc( sizeof(Node) * COL_NUM); 

释放的顺序必须是相反的:首先为每个table[i]循环free

您需要先分配表,然后分配每一行:

 table = malloc(sizeof(Node*)*2); for (int i=0; i<2; i++) table[i] = malloc(sizeof(Node)*x); 

当你完成使用它时,不要忘记释放这个内存:

 for (int i=0; i<2; i++) free(table[i]); free(table); 

总结和调整,它应该是这样的:

Node.h

 #ifndef NODE_H #define NODE_H typedef void * DataP; struct Node { DataP data; void * key; } #endif 

Node.c

 #include  /* for malloc () and free() */ #include  /* for errno */ #include "node.h" void nodes_free(struct Node ** ppNode, size_t rows) { if (!ppNode) { return; } for (size_t row = 0; row < rows; ++row) { free(ppNode[row]); } free(ppNode); } int nodes_allocate(struct Node *** pppNode, size_t rows, size_t columns) { if (!pppNode && !*pppNode) { errno = EINVAL; return -1; } *pppNode = malloc(rows * sizeof **pppNode); if (!*pppNode) { perror("malloc() failed on allocating rows"); return -1; } { size_t row = 0 for (; row < rows; --row) { (*pppNode)[row] = malloc(columns * sizeof *(*pppNode)[row]); if (!*pppNode[row]) { perror("malloc() failed on allocating columns"); break; } } if (row < rows) /* Allocation of columns did not completed successfully, clean up and leave. */ { nodes_free(*pppNode, row); return -1; } } return 0; } 

使用这样的function:

 #include  /* for EXIT_xxx macros */ #include  /* for perror() */ #include "node.h" #define ROWS (5) #define COLUMNS (7) int main(void) { struct Node ** ppNode; if (-1 == nodes_allocate(&ppNodes, ROWS, COLUMNS); { perror("nodes_allocate() failed"); return EXIT_FAILURE; } /* Do stuff. */ /* clean up. */ nodes_free(*ppNodes, ROWS); return EXIT_SUCCESS; }