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

Asked

Viewed 426 times

0

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

  • 1

    Take a look at the answers to this question that shows how you can use the malloc to allocate memory as needed.

  • Did you try to do anything? It’s not very secret. Do you have any specific questions?

1 answer

0

Here are two possible solutions to your problem:

1) Solution with dynamic vector allocation with functions malloc() and free() of the standard 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) permitted from the standard 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’ve helped!

  • But in the solution (2) the array v will not be local to main function?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.