2

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

3 Answers3

1
struct mystruct *s = malloc(sizeof(*s));
s->size = 5;
s->t = malloc(sizeof(*s->t) * s->size);
Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
  • Ok, edited the question with sample code, which seems to be doing exactly as all the answers are suggesting - get a seg fault on the line "if (m->t = malloc(m->size * sizeof(*m->t)) == NULL)" – John Richards Oct 27 '10 at 11:54
  • Actually, seems the seg fault is the line setting the size - according to gdb – John Richards Oct 27 '10 at 11:56
  • first line should be struct mystruct *s = malloc(sizeof(s)); otherwise it allocates ONLY the space needed for a pointer (you wrote sizeof(*s)) – Daniele Santi Oct 27 '10 at 12:21
  • @Mr Shunz: No. The type of `*s` is `struct mystruct`, not `struct mystruct *`. IOW, `sizeof *s` == `sizeof (struct mystruct)`. – John Bode Oct 27 '10 at 14:11
  • @John Richards: You're getting bitten by a precedence issue; expressions of the form `a = b == c` are parsed as `a = (b == c)`, which is not what you want here. You need to explicitly group the assignment as `(a = b) == c`. – John Bode Oct 27 '10 at 14:17
0

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:

if ( (m = (MyStruct *)malloc(sizeof(MyStruct))) == NULL)
...
if ( (m->t = malloc(m->size * sizeof(*m->t))) == NULL) 
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

That happens because you do not allocate memory for array itself, only for pointer to this array.

So, first you have to allocate mystruct:

struct_instance = malloc(sizeof(mystruct));

and then you have to allocate memory for array of pointers to MyDef and initialize pointer in your struct

struct_instance->size = 123;
struct_instance->t = malloc(sizeof(MyDef*) * struct_instance->size);
Kel
  • 7,680
  • 3
  • 29
  • 39