How to declare and initialize this array of structures in C when the length is unknown before 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 is declared in foo.h.)

This code should be executed without hard coding of the number for bars, since the number of bars will change depending on the user setting their DIP switches. Right now I cannot initialize myFoo; I get the error "constant expression expected in initializer". Should I initialize it like this:

struct foo myFoo[];

and change it later? If so, how do I make myFoo [] the correct length? I obviously don't have a constant that matches the size I want. Do I need to dynamically highlight this or something else?

, - ++ , ,

+3
3
struct foo* myFoo;
unsigned int myFooSize;

void initMyFoo(void)
{
  myFooSize = getNumBars();
  myFoo = malloc(myFooSize * sizeof(*myFoo));
  for (i=0; i<myFooSize; i++) {
    /* ... */
  }
}

void cleanupMyFoo(void)
{
  free(myFoo);
  myFoo = NULL;
  myFooSize = 0;
}
+3

1 - C99 , , . (GCC -C99 C ++), .

int someUnknownSize = 0;

/* some code that changes someUnknownSize */

struct foo myFoo[someUnknownSize];

2 - , malloc calloc.

struct foo *fooPtr = 0; /* null pointer to struct foo */
int sizeToAlloc = 0;
/* determine how much to allocate/modify sizeToAlloc */
fooPtr = malloc(sizeToAlloc * sizeof(*fooPtr));

/* do stuff with the pointer - you can treat it like you would an array using [] notation */
free(fooPtr);
+1

I usually use the expected maximum size of the array, and if necessary, just resize it:

type * a = calloc(sizeof(type),exp_array_size);

and when pushing a new value to the array (duck, OK, I consider it as if it were a stack ...), I check its current size for a new one:

if (current_size > max_size) {
    max_size *= 2;
    realloc(a,max_size*sizeof(type));
}
0
source

Source: https://habr.com/ru/post/1778176/


All Articles