0

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'

1
  • A more interesting adventure is what compiler you're using that allows an initial value assignment to a VLA. None of mine do (clang and msvc), so if Struct *Pointer[c] = {NULL}; "works" I'm curious as to how. I assume the Pointer vs pointer different is just a typo (that I also don't understand, as there is literally no "typing" to introduce a "typo" when copy/pasting what is supposed to be functioning code). Commented Apr 25, 2021 at 19:01

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Hey Mike - Thank you for your answer - You are right - I miss typed sizeof(pointer) to sizeof(Struct)...ah...I am so dumb!!!!!!! I found that I can not use Struct *Pointer[c] = {NULL} as the C is a variable - the compiler won't let me do it.
@0___________ Sorry Mate it was my bad - I should't have {NULL}, in C it doesn't work that way
@0___________ This can be valid.
1
memset(Pointer, 0, sizeof(Pointer));

or

memset(Pointer, 0, c * sizeof(*Pointer));

Spot the difference.

You can answer your question yourself if you put some research effort and printed out the sizeof(Pointer) and calculate why c * sizeof(Pointer) is wrong.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.