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

时间:2016-08-21 17:04:52

标签: c arrays pointers malloc

所以我得到了struct Node,其中包含2个字段: DataP datavoid * keyDataP只是typedef的{​​{1}}。

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

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

我试过Node **table 但这是对的吗?以及如何从这里继续?

4 个答案:

答案 0 :(得分:2)

  

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

你正在以正确的方式做到这一点。现在您有两个Node*类型table[0]table[1]

的变量

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

  

如何从这里继续?

现在使用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);

答案 1 :(得分:1)

大小为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);

解除分配顺序必须颠倒:首先free为每个table[i]循环

答案 2 :(得分:0)

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

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);

答案 3 :(得分:0)

总结和调整,它应该如下所示:

Node.h

#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* 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;
}

Node.c

;With cte
as
(select 
itemnumber,saledate,dense_rank() over (partition by  itemnumber order by cast(month(saledate) as varchar(2))+'/'+cast(year(saledate) as varchar(4)) ) as rownum
from
@sales
)
select itemnumber,cast(month(saledate) as varchar(2))+'/'+cast(year(saledate) as varchar(4)),sum(rownum) as salescount

from cte
where rownum=1
group by
itemnumber,cast(month(saledate) as varchar(2))+'/'+cast(year(saledate) as varchar(4))

使用以下功能:

{{1}}
相关问题