简体   繁体   English

在 c 中初始化双指针的正确方法是什么

[英]What is the right way to initialize double pointer in c

As title, I want to know how to initialize double pointer with sizeof a pointer.作为标题,我想知道如何用sizeof指针初始化双指针。

For instance例如

int **p=malloc(sizeof *p * rows);

for(size_t i = 0; i < rows; i++){
    p[i]=malloc(sizeof ? * cols);
}

What should I fill in ?我应该填写? . .

Any help would be appreciated.任何帮助,将不胜感激。

It looks like you want p to be an array that can hold pointers, and the number of pointers is rows .看起来您希望p是一个可以保存指针的数组,并且指针的数量是rows So you can allocate memory for p like this:所以你可以像这样为p分配 memory :

int ** p = malloc(sizeof(int *) * rows);

Now if you want p[i] to point to an array that holds cols ints, do this:现在,如果您希望p[i]指向包含cols整数的数组,请执行以下操作:

p[i] = malloc(sizeof(int) * cols);

What should I fill in?.我应该填写什么?

In general when you have一般来说,当你有

X = malloc(sizeof ? * NUMBER);

the ? ? is to be replaced with the type that X points to.将替换为X指向的类型。 That can simply written as *X .这可以简单地写为*X

So the line:所以这一行:

p[i]=malloc(sizeof ? * cols);

is to be:是:

p[i]=malloc(sizeof *p[i] * cols);

Notice that a 2D array can be created much simpler.请注意,可以更简单地创建 2D 数组。 All you need is所有你需要的是

int (*p)[cols] = malloc(sizeof *p * rows);

Here p is a pointer to an array of cols int .这里p是指向cols int数组的指针。 Consequently sizeof *p will be the size of an array of cols int .因此sizeof *p将是cols int数组的大小。

Using this VLA based technic means that you can allocate the 2D array using a single malloc使用这种基于 VLA 的技术意味着您可以使用单个malloc分配二维阵列

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

相关问题 在c中初始化指针的正确方法是什么? - What is the correct way to initialize a pointer in c? 在C中创建和初始化包含函数指针的结构的正确方法是什么? - What is the right way of creating and initializing a struct containing a function pointer in C? 初始化指向struct的指针数组的正确方法是什么? - What is the correct way to initialize an array of pointer to struct? 在C中将浮点指针重铸为双指针的最有效方法是什么? - What's the most efficient way to recast a float pointer as a double pointer in C? 有没有办法初始化指向C中数组的指针(在同一行上) - Is there a way to initialize a pointer to an array in C (on the same line) 如何在 C 中初始化双指针? (指针数组) - How do I initialize a double pointer in C? (array of pointers) 将指针传递给我的 function 的正确方法是什么? - What is the right way to pass a pointer to my function? 在C中释放双指针的干净方法 - Clean way to free double pointer in c 在C和Objective-C中,截断float或double的正确方法究竟是什么? - In C and Objective-C, what really is the right way to truncate a float or double to an integer? C中的struct的双指针是什么意思 - what is the meaning of a double pointer of struct in C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM