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

210
Visualizações
How can static array in C taking size in runtime?

I am mindblown by this small code:

#include <stdio.h>

    int main()
    {
        int limit = 0;
        scanf("%d", &limit);
        int y[limit];
        
        for (int i = 0; i<limit; i++ ) {
            y[i] = i;
        }
        
        for (int i = 0; i < limit; i++) {
            printf("%d ", y[i]); 
        }
    
        return 0;
    }

How on earth this program is not segment-faulting as limit (size of the array) is assigned at runtime only?

Anything recently changed in C? This code shouldn't work in my understanding.

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

0

int y[limit]; is a Variable Length Array (or VLA for short) and was added in C99. If supported, it allocates the array on the stack (on systems having a stack). It's similar to using the machine- and compiler-dependent alloca function (which is called _alloca in MSVC):

Example:

#include <alloca.h>
#include <stdio.h>

int main()
{
    int limit = 0;
    if(scanf("%d", &limit) != 1 || limit < 1) return 1;

    int* y = alloca(limit * sizeof *y); // instead of a VLA

    for (int i = 0; i<limit; i++ ) {
        y[i] = i;
    }

    for (int i = 0; i < limit; i++) {
        printf("%d ", y[i]);
    }
} // the memory allocated by alloca is here free'd automatically

Note that VLA:s are optional since C11, so not all C compilers support it. MSVC for example does not.

over 4 years ago · Santiago Trujillo Relatório

0

This doesnt compile in visual studio because limit "Error C2131 expression did not evaluate to a constant"

If you make limit a constexpr though then the compiler will not mind because youre telling it it wont change. You cant use 0 though as setting an array to a constant size length zero is nonsence.

What compiler does this run on for you ?

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