Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init struct pointer variables with NULL?

Tags:

c

I have such two struct

struct table_element
{
    struct table_val * table_val_arr;
    int count_arr;
};

struct hash_table
{
    struct table_element table_element_arr[MAX_NUMBER];
};

and here my test method

void test(struct hash_table * table)
{
    int count;
    struct table_element * tab_element;

    for(count = 0; count < MAX_NUMBER; count++)
    {
        tab_element = &table->table_element_arr[count]; 

        if(tab_element->table_val_arr == NULL)
        {
            printf("\nNULLLL!!!!!\n");
        }
        else
        {
            printf("\nOK!!!!!\n");
        }
    }
}

and here how I use it

int main(int argc, char **argv)
{
    struct hash_table m_hash_table;

    test(&m_hash_table);
...

I expect that all value would be NULL, but sometimes I get OK sometimes NULL...

What am I doing wrong?

How to init it with NULL?

like image 369
Aleksey Timoshchenko Avatar asked Aug 06 '26 07:08

Aleksey Timoshchenko


1 Answers

Non-static variables defined inside of a function have indeterminate values if not explicitly initialized, meaning you can't rely on anything they may contain.

You can fix this by giving an initializer for the variable:

struct hash_table m_hash_table = {{NULL, 0},{NULL, 0},/*repeat MAX_NUMBER times*/};

Or by using memset:

memset(&m_hash_table, 0, sizeof(m_hash_table));
like image 154
dbush Avatar answered Aug 08 '26 22:08

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!