Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
Integer array size in C without using dynamic memory allocation

I need to declare an array of structures with size symbolnum, but because symbolnum is variable C will produce an error when i write the following code:

extern int symbolnum;

struct SymbTab stab[symbolnum];

I already tried:

extern int symbolnum;
const int size = symbolnum;
struct SymTab stab[size];

Is there a way to achieve this without using dynamic memory allocation functions like malloc() or initializing the size of array using a very big number?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The size of global arrays must be fixed at compile time. VLAs are only allowed inside of functions.

If the value of symbolnum isn't known until runtime, you'll need to declare stab as a pointer type and allocate memory for it dynamically.

Alternately, if the array doesn't take up more than a few 10s of KB, you can define the VLA in the main function and set a global pointer to it.

over 4 years ago · Santiago Trujillo Relatório

0

C11 and later permit variable-length arrays as an optional feature. C99 permitted them as a mandatory feature. However, in no case are VLAs permitted at file scope, which appears to be what you are trying to achieve.

And file-scope VLAs wouldn't make sense in light of C semantics anyway. Objects declared at file scope have static storage duration, meaning that they come into existence at or before the beginning of program execution, and live until program termination. That means the array length is needed before the variable can take anything other than its initial value (which is zero or an integer constant expression), so one might as well just use that initial value directly.

Additionally, some C implementations (notably MSVC) never implemented VLAs even when C99 was the current standard, and have no intention to do so now that the feature is optional in the current standard.

So,

Is there a way to achieve this without using dynamic memory allocation functions like malloc() or initializing the size of array using a very big number?

It depends a bit on your exact needs (and on your C implementation), but likely not. One possibility would be to use a local VLA in main(), or in some other function whose execution encompasses the whole need for the array. If your C implementation supports it them you could declare a VLA there, and pass around a pointer to that. But note well that if the upper bound on the number of elements you need is really "a very large number" then this is unlikely to be suitable. VLAs are typically allocated on the stack, which puts a relatively tight bound on how large they can be.

over 4 years ago · Santiago Trujillo Relatório

0

"Is there a way to achieve this without using dynamic memory allocation functions like malloc() or initializing the size of array using a very big number?"

If you can use variable length array (VLA), then yes it can be done. The following illustrates one way...

With a struct definition in global space, (eg, top of .c file, or in .h file) local array instances of that struct can be created using a VLA, keeping in mind the stipulations mentioned in the link for using VLA. The VLA struct array can then be passed as a function parameter, to either be used in the called function, or to be updated and returned, just as any other function parameter is used. Here is a simple example:

//define either at top of .c file in file global space
//or in a header file that is included in any .c.  Then
//the typedef num_s can be used to create instances where needed
//
typedef struct SymbTab{
    int iVal;
    double dVal;
} SymbTab_s;

void populate_struct(size_t symbolnum, SymbTab_s *stab);

int main(void)
{
    size_t symbolnum = 0;//(using size_t). note, as you describe, this 
                         //comes after flex analysis normally, but for 
                         //this demo user input is used for simple 
                         // example of dynamically sizing array.
    printf("Enter symbolnum of struct array:\n");
    scanf("%zu", &symbolnum);
    SymbTab_s stab[symbolnum]; //dynamically sized array of SymbTab_s
    memset(stab, 0, sizeof(SymbTab_s) * symbolnum); //initialize new array
    populate_struct(symbolnum,  stab); //pass as function argument and update values
    //demo updated values
    for(int i=0; i < symbolnum; i++)
    {
        printf("%d, %lf\n", stab[i].iVal, stab[i].dVal);
    }
    return 0;
}

//simple function to demo form of parameters
//note size parameter is passed first
void populate_struct(size_t symbolnum, SymbTab_s *stab)
{
   for(int i=0; i < symbolnum; i++)
   {
       stab[i].iVal = i;
       stab[i].dVal = 1.0*i;
   }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda