Search code examples
arrayscpointersinitializationmemset

Memset function in C initialised all the arrays


I was trying to initialise a array made by pointer:

the code I used was:

    int c = 15;
    Struct *Pointer[c] = {NULL};
    memset( pointer, 0, c *sizeof(pointer) );

It worked, But this memset() function not only initialised my Pointer array, but also initialise all my other arrays...

is there any way to fix it?

I can not use for(){} or while function as it will increase my Time complixcity...

Cheers'


Solution

  • sizeof(pointer) is the size of the entire array pointer. Multiplying integers larger than 1 to that for size to memset() will cause out-of-range access.

    Remove the harmful multiplication.

    int c = 15;
    Struct *Pointer[c] /* = {NULL} */; /* VLA cannot be initialized */
    
    /* some other code that uses Pointer */
    
    memset(Pointer, 0, sizeof(Pointer));