-1

I want to create a vec of structures. This is my struct:

    typedef struct item {
        char *name;
        int acc;
    } *Item;

I tried:

    Item vec = (Item) malloc(sizeof(Item)*max);

max is previously defined. I get this error: initializer element is not constant

Vera
  • 1
  • 1
  • 5
    `typedef struct item { ... } * Item;` Is a terrible idea. – Iharob Al Asimi May 13 '16 at 19:10
  • Think what `sizeof(Item)` does, given it is a pointer type... – Eugene Sh. May 13 '16 at 19:11
  • @EugeneSh. One of the reasons why my comment is sooo true. – Iharob Al Asimi May 13 '16 at 19:11
  • Is `vec` a global variable? (btw, I agree with iharob that you should never typedef a pointer.) And there's also [this](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – user3386109 May 13 '16 at 19:14
  • 4
    BTW, the error message is completely unrelated to the code you posted. If you really want help, post the code. – Iharob Al Asimi May 13 '16 at 19:19
  • @iharob originally we were going for what is suggested in the answer. But on the tips for this project it was said that the way that we used "allows a propper abstraction". That's the only reason why we used it. – Vera May 13 '16 at 20:17
  • @iharob and no, the error message is not completely unrelated to the code I posted `draft3.c:28:12: error: initializer element is not constant Item vec = (Item) malloc(sizeof(Item)*max);` – Vera May 13 '16 at 20:28
  • @user3386109 yes, vec is a global variable. So it's impossible to do what I was trying? – Vera May 13 '16 at 20:29
  • 1
    Yup, local variables can be initialized with function calls, but global variables cannot. Globals can only be initialized with compile-time constants. If `max` is a constant, then `vec` could be declared as an array: `struct item vec[max];`. Otherwise, you need to call `malloc` at some point after the value of `max` has been determined. – user3386109 May 13 '16 at 20:33
  • See [Is it a good idea to typedef pointers](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — the short answer is "No"; the marginally longer answer is "No, unless perhaps it is a function pointer". – Jonathan Leffler May 14 '16 at 20:44

1 Answers1

1

Change it by:

typedef struct item {
    char *name;
    int acc;
} Item;

(no pointer) and then do sizeof(struct item) or sizeof(Item). Then

Item *vec = malloc(sizeof(Item) * max);
rodolk
  • 5,606
  • 3
  • 28
  • 34