Home > Mobile >  Declare and initialize after
Declare and initialize after

Time:08-11

I'm working on an exercise and I can't declare and initialize on the same line, and with these instructions I don't know how I can do, I tried multiple tips but no one works. Can you help me please ? I want to initialize my array in the next line. This, is working fine:

int tab[n];

tab[0] = 5;

And, this, is not working

int tab[];

tab[n] = { 0 };

CodePudding user response:

Issue #1. The compiler needs a size when declaring an array.

int tab[];

Will not compile.

C does allow for variable sized arrays.

int n = 5;
int tab[n];

Issue #2. You attempt to assign to the nth element in an array with size n, which is out of bounds, and will not work.

Issue #3. You cannot assign to an array directly, so this will not work:

int n = 5;
int tab[n];

tab = { 0 };

And the initializer syntax will not work in this context. You would have to use it inline with the declaration. Although, a variable-sized array may not be initialized this way anyway.

Legal:

#define N 5

int main() {
    int tab[N] = { 0 };

    return 0;
}

Illegal:

int main() {
    int n = 5;
    int tab[n] = { 0 };

    return 0;
}

CodePudding user response:

To assign an all zero byte pattern to int tab[n] after definition:

memset(tab, 0, sizeof tab);

If code needs a more complex assignment, code could then use individually for each array element as needed.

tab[0] = 5;
...

CodePudding user response:

C has something which is called flexible array members.

struct flex
{
    size_t size;
    int x[];
};

struct flex a = {5, {1,2,3,4,5}};

int main(void)
{
    struct flex *z;

    z = malloc(sizeof(*z)   3 * sizeof(z -> x[0]));
    z -> size = 3;    
}
  •  Tags:  
  • c
  • Related