How to declare and initialize this array of structs in C when the length is not known till runtime? -


foo.c

#include "main.h" unsigned char currentbar; struct foo myfoo[getnumbars()];  void initmyfoo(void) {  currentbar=(getnumbars()-1);  for(i=0; i<(sizeof(myfoo)/sizeof(myfoo[0])); i++)  {   myfoo[i].we = 1;   myfoo[i].want = 0;   myfoo[i].your = 0;   myfoo[i].soul = 0;  } } 

main.c

#include "foo.h" unsigned char getnumbars() {  return getdipswitchvalues(); } initmyfoo(); 

(struct foo declared in foo.h.)

this code has execute without hard coding number bars, number of bars change according whatever user sets dip switches. right i'm not able initialize myfoo; error "constant expression expected in initializer." have initialize like:

struct foo myfoo[]; 

and change later? if so, how make myfoo[] correct length? don't have constant available corresponds desired size. need dynamically allocate or something?

i found similar answer wasn't helpful me - c++ class array of structs, without knowing how large array need

struct foo* myfoo; unsigned int myfoosize;  void initmyfoo(void) {   myfoosize = getnumbars();   myfoo = malloc(myfoosize * sizeof(*myfoo));   (i=0; i<myfoosize; i++) {     /* ... */   } }  void cleanupmyfoo(void) {   free(myfoo);   myfoo = null;   myfoosize = 0; } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -