简体   繁体   English

如何初始化C语言中的指针

[英]How to Initialize a pointer to a pointer in C

So I got this struct Node which contains 2 fields: DataP data , void * key , DataP is just a typedef for void* . 所以我得到了包含2个字段的struct NodeDataP datavoid * keyDataP只是void*typedef

I created a double pointer Node **table to make it like a 2D array. 我创建了一个双指针Node **table ,使其像一个2D数组。

I can't figure how to malloc it, I want this double pointer to act as a 2D array with 2 as number of rows and x as number of cols. 我无法弄清楚如何对其进行分配,我希望此双指针充当2D数组,其中2作为行数,x作为cols数。

I've tried table = (Node**)malloc(sizeof(Node*)*2); 我已经尝试过table = (Node**)malloc(sizeof(Node*)*2); but is this correct? 但这是正确的吗? and how do I continue from here? 以及如何从这里继续?

I've tried table = (Node**)malloc(sizeof(Node*)*2); 我已经尝试过table = (Node**)malloc(sizeof(Node*)*2); but is this correct? 但这是正确的吗?

YES you're doing it the right way. 是的,您的做法正确。 Now you've two variables of the type Node* which are table[0] and table[1] 现在,您有两个Node*类型的变量,分别是table[0]table[1]

Note that you need not cast the return value of malloc() . 请注意,您无需malloc()的返回值。 Here's why : click 这是原因: 点击

and how do I continue from here? 以及如何从这里继续?

Now use a for loop to assign memory to the above two variables 现在使用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()
}

so next time you want to allocate memory to a double pointer, you can do it this way : 因此,下次您要将内存分配给双指针时,可以采用以下方式:

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

Order of allocation memory for table of size ROW_NUM x COL_NUM should be the following: 大小为ROW_NUM x COL_NUM的表的分配内存顺序应为:

1) Memory for array of pointers: 1)指针数组的内存:

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

2) Memory for each row (loop needed) 2)每行的内存(需要循环)

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

Order of deallocation have to be reverse: loop with free for each table[i] first 解除分配的顺序必须被反向:与循环free对每个table[i]第一

You need to allocate the table first, and then allocate each one of the rows: 您需要首先分配表,然后分配每行:

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

And don't forget to deallocate this memory when you're done using it: 使用完后,不要忘记分配此内存:

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

Summarising and tweaking, it should look like this: 总结和调整,它应该像这样:

Node.h Node.h

#ifndef NODE_H
#define NODE_H

typedef void * DataP;

struct Node 
{
  DataP data; 
  void * key;
}


#endif

Node.c 节点

#include <stdlib.h> /* for malloc () and free() */
#include <errno.h> /* 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;
}

Use those functions like this: 使用如下功能:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM