如何将malloc“MyDef ** t”改为特定长度,而不是C中的“MyDef * t [5]”

时间:2010-10-27 11:34:38

标签: c pointers malloc calloc

如下所示的结构很好,我可以在调用 malloc(sizeof(mystruct))后使用 t

struct mystruct {
 MyDef *t[5];
};

我希望能够动态设置 MyDef 数组的长度,如下所示:

struct mystruct {
 MyDef **t;
 int size;
};

除了 malloc(sizeof(mystruct))之外我还需要做些什么才能让它工作,所以我可以做 TestStruct-> t [3] =某事?只是出现分段错误!

谢谢!

编辑代码导致seg错误,除非我是盲目的,这似乎是答案到目前为止:

#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;
}

3 个答案:

答案 0 :(得分:1)

struct mystruct *s = malloc(sizeof(*s));
s->size = 5;
s->t = malloc(sizeof(*s->t) * s->size);

答案 1 :(得分:0)

m =(MyStruct *)malloc(sizeof(MyStruct))== NULL

那是做什么的。调用malloc,将malloc的返回值与NULL进行比较。然后将该比较的结果(布尔值)分配给m。

之所以这样做是因为'=='的优先级高于'='。

你想要什么:

if ( (m = (MyStruct *)malloc(sizeof(MyStruct))) == NULL)
...
if ( (m->t = malloc(m->size * sizeof(*m->t))) == NULL) 

答案 2 :(得分:0)

这是因为您没有为数组本身分配内存,仅用于指向此数组的指针。

所以,首先你必须分配mystruct:

struct_instance = malloc(sizeof(mystruct));

然后你必须为指向MyDef的指针数组分配内存并在结构中初始化指针

struct_instance->size = 123;
struct_instance->t = malloc(sizeof(MyDef*) * struct_instance->size);