How to change the size of a global vector of structures in C?

0

My idea is to declare a global vector of a x-structure, but I will only have the size of the vector in main. How can I declare the vector and then tell it the size of it? I have an equivalent solution in Java, but not in C.

    
asked by anonymous 20.08.2016 / 22:34

1 answer

0

Here are two possible solutions to your problem:

1) Solution with dynamic vector allocation with the malloc() and free() functions of the default library stdlib.h :

#include <stdlib.h>

typedef struct foobar_s
{
    int a;
    int b;
    int c;
} foobar_t;


int main( int argc, char * argv[] )
{
    foobar_t * v = NULL;
    int n = 0;
    int i = 0;

    /* Recupera tamanho do vetor passado como parametro na linha de comando */
    n = atoi( argv[1] );

    /* Aloca memoria necessaria para armazenar o vetor */
    v = (foobar_t*) malloc( n * sizeof(foobar_t) );

    /* Inicializa todos os membros de cada elemento do vetor com o valor '0' */
    for( i = 0; i < n; i++ )
    {
        v[i]->a = 0;
        v[i]->b = 0;
        v[i]->c = 0;
    }

    /* Faz alguma coisa com o vetor... */

    /* Libera memoria alocada */
    free( v );

    return 0;
}

/* fim-de-arquivo */

2) Solution with static vector allocation using VLAs (Variable Length Array) allowed from default C99 :

typedef struct foobar_s
{
    int a;
    int b;
    int c;
} foobar_t;


int main( int argc, char * argv[] )
{
    int n = 0;
    int i = 0;

    /* Recupera tamanho do vetor passado como parametro na linha de comando */
    n = atoi( argv[1] );

    /* Declara vetor estaticamente com tamanho 'n' */
    foobar_t v[ n ];

    /* Inicializa todos os membros de cada elemento do vetor com o valor '0' */
    for( i = 0; i < n; i++ )
    {
        v[i].a = 0;
        v[i].b = 0;
        v[i].c = 0;
    }

    /* Faz alguma coisa com o vetor... */

    return 0;
}

/* fim-de-arquivo */

I hope I have helped!

    
22.08.2016 / 21:14