如何初始化指向C中的指针的指针 [英] How to Initialize a pointer to a pointer in C

查看:62
本文介绍了如何初始化指向C中的指针的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到了这个包含两个字段的struct Node: DataP datavoid * keyDataP只是void*typedef.

So I got this struct Node which contains 2 fields: DataP data, void * key, DataP is just a typedef for void*.

我创建了一个双指针Node **table使其类似于2D数组.

I created a double pointer Node **table to make it like a 2D array.

我无法弄清楚如何对其进行分配,我希望此双指针充当2D数组,其中2作为行数,x作为cols数.

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.

我已经尝试过table = (Node**)malloc(sizeof(Node*)*2); 但这是正确的吗?以及如何从这里继续?

I've tried table = (Node**)malloc(sizeof(Node*)*2); but is this correct? and how do I continue from here?

推荐答案

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

I've tried table = (Node**)malloc(sizeof(Node*)*2); but is this correct?

,您的做法正确.现在,您有两个Node*类型的变量,分别是table[0]table[1]

YES you're doing it the right way. Now you've two variables of the type Node* which are table[0] and table[1]

请注意,您不必强制转换malloc()的返回值.原因如下: 点击

Note that you need not cast the return value of malloc(). Here's why : click

以及如何从这里继续?

and how do I continue from here?

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

Now use a for loop to assign memory to the above two variables

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

这篇关于如何初始化指向C中的指针的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆