1

i read already some answers on stackoverflow but I don't know why it still doesn't work :

typedef struct gnl_struct {
    char        *data;
    int         where;
    int         status;
}               t_gnl;

void display_elem(t_gnl tab, int nbr)
{
    printf("tab[%d]\n", nbr);
    printf("tab.where == %d\n", tab.where);
    printf("tab.status == %d\n", tab.status);

    return ;
}

int     main()
{
    static t_gnl    tab[1000] = {{ "toto", 0, 2 }} ;

    display_elem(tab[3], 3);

    return (0);
}

the result is :

tab[3]
tab.where == 0
tab.status == 0
decarte
  • 410
  • 1
  • 7
  • 17

2 Answers2

4

In your code, you've (yourself) initalized only tab[0] and you're passing tab[3]. All the other elements in the array [tab[1] to tab[999]] are auto initalized to 0.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • @hadesMM I suggest use a loop (if you really need 1000 elements), or don't use an array, if you want only a single variable. – Sourav Ghosh Apr 23 '15 at 14:42
  • 2
    even if it is not static , the initlaizer ensures all the elements initialized to zero. – bare_metal Apr 23 '15 at 14:43
  • @bare_metal Right, I'll remove that misleading part. – Sourav Ghosh Apr 23 '15 at 14:43
  • 1
    besides that, your compiler should complain (with a warning at least) about missing braces... – mfro Apr 23 '15 at 14:43
  • Thx, for your answers, I need the tab, so how can i loop for a static variable ? (i need to initialize on the same line right ?) – decarte Apr 23 '15 at 14:46
  • 2
    @hadesMM You can initialize it like [this](http://stackoverflow.com/questions/21528288/c-structure-array-initializing). But please note that allocating 1000 structs statically is not a good idea on most systems. For large amounts of data, you should allocate the memory on the heap instead. – Lundin Apr 23 '15 at 14:46
  • @SouravGhosh The original post was kind of right though, because the standard says that the remaining elements of the array as initialized "as if they had static storage duration". Which will happen no matter the storage duration of the array itself. – Lundin Apr 23 '15 at 14:53
  • @Lundin True sir. under the hood it's `as if static`, but without the `static` keyword also, in this particular case, the remaining array elements will be 0 filled. So, to avoid any possible confusion, i kep the `static` part out. :-) – Sourav Ghosh Apr 24 '15 at 05:41
0

You have initialized only the first array element, so the remaining will implicitly get filled with 0. Now when you try to print the third element then it will be zero.

Lundin
  • 195,001
  • 40
  • 254
  • 396
Karthick
  • 1,010
  • 1
  • 8
  • 24