如何分配“MyDef ** t”到特定长度,而不是“MyDef * t[5]”在C中
像下面这样的结构工作正常,我可以在调用 malloc(sizeof(mystruct)) 后使用 t:
struct mystruct {
MyDef *t[5];
};
我希望能够动态设置数组的长度MyDef,如下所示:
struct mystruct {
MyDef **t;
int size;
};
除 malloc(sizeof(mystruct)) 之外,我还需要做什么才能使其正常工作,这样我就可以执行 TestStruct- >t[3] = 某事?只是出现分段错误!
谢谢!
使用导致段错误的代码进行编辑,除非我是盲人,否则这似乎是迄今为止的答案:
#include <stdio.h>
typedef struct mydef {
int t;
int y;
int k;
} MyDef;
typedef struct mystruct {
MyDef **t;
int size;
} MyStruct;
int main(){
MyStruct *m;
if (m = (MyStruct *)malloc(sizeof(MyStruct)) == NULL)
return 0;
m->size = 11; //seg fault
if (m->t = malloc(m->size * sizeof(*m->t)) == NULL)
return 0;
return 0;
}
A struct like the following works fine, I can use t after calling malloc(sizeof(mystruct)):
struct mystruct {
MyDef *t[5];
};
I want to be able to dynamically set the length of the array of MyDef, like the following:
struct mystruct {
MyDef **t;
int size;
};
What do I need to do additionally to malloc(sizeof(mystruct)) to get this to work, so I can do TestStruct->t[3] = something? Just getting a segmentation fault!
Thanks!
EDIT with code that causes seg fault, unless I'm blind this seems to be what the answers are so far:
#include <stdio.h>
typedef struct mydef {
int t;
int y;
int k;
} MyDef;
typedef struct mystruct {
MyDef **t;
int size;
} MyStruct;
int main(){
MyStruct *m;
if (m = (MyStruct *)malloc(sizeof(MyStruct)) == NULL)
return 0;
m->size = 11; //seg fault
if (m->t = malloc(m->size * sizeof(*m->t)) == NULL)
return 0;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
m = (MyStruct*)malloc(sizeof(MyStruct)) == NULL
这是做什么的。调用 malloc,将 malloc 的返回值与 NULL 进行比较。然后将该比较的结果(布尔值)分配给 m。
这样做的原因是因为“==”的优先级高于“=”。
你想要什么:
m = (MyStruct*)malloc(sizeof(MyStruct)) == NULL
What that does. Calls malloc, compares return of malloc to NULL. Then assigns the result of that comparison(a boolean value) to m.
The reason it does that is because '==' has a higher precedence than '='.
What you want:
发生这种情况是因为您没有为数组本身分配内存,而只为指向该数组的指针分配内存。
因此,首先必须分配 mystruct:
然后必须为指向 MyDef 的指针数组分配内存并初始化结构中的指针
That happens because you do not allocate memory for array itself, only for pointer to this array.
So, first you have to allocate mystruct:
and then you have to allocate memory for array of pointers to MyDef and initialize pointer in your struct