[英]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.