版本 1:
struct mydef_s1 {
int argc;
char *argv[3];
};
struct mydef_s1 *p1 = (struct mydef_s1*) malloc (sizeof (struct mydef_s1));
p1->argv[0] = malloc (8);
p1->argv[1] = malloc (16);
p1->argv[2] = malloc (24);
Now, I want to achieve above with the following structure declaration?
版本 2:
struct mydef_s2 {
int argc;
char **argv;
};
如果我是对的,那么下面只想分配 8 个字节(4 个用于内存指针,4 个用于我的机器中的整数)
struct mydef_s2 *p2 = (struct mydef_s2*) malloc (sizeof (struct mydef_s2));
我应该怎么做才能执行以下操作?
p2->argv[0]= malloc(4);
p2->argv[1]=malloc(8);
最佳答案
对于像这样的指针的情况
struct mydef_s2 {
int argc;
char **argv;
};
您必须首先为 argv
本身分配内存,然后为 argv[i]
分配内存。
类似于(代码没有错误检查)
argv = malloc(n * sizeof*argv); //allocate memory to hold 'n' number of 'argv[i]'s
for (i = 0; i < n; i++)
argv[i] = malloc(32); //allocate individual `argv[i]`s
会完成这项工作。
关于c - 如何使用双指针作为指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37410995/