Page 1 of 1

C allocate and initialize in same statement

Posted: Wed Mar 09, 2022 5:38 pm
by PavelChekov
I am looking to allocate and initialize an array in the same statement. Not like calloc, where the members are initialized to 0, but to, say, 1, 2, and 3. (If it restricts anything, I want to do this to initialize a member of a struct.)

Thanks

Re: C allocate and initialize in same statement

Posted: Wed Mar 09, 2022 6:13 pm
by Octocontrabass
You can't dynamically allocate and initialize an array in the same statement. Static and automatic allocation is fine, though. You need more braces if the array is a struct member.

Re: C allocate and initialize in same statement

Posted: Thu Mar 10, 2022 11:02 am
by iansjack
As malloc can fail this would be very bad practice - even if it was allowed.

Why do you need to restrict it to a single statement?