C allocate and initialize in same statement

Programming, for all ages and all languages.
Post Reply
User avatar
PavelChekov
Member
Member
Posts: 113
Joined: Mon Sep 21, 2020 9:51 am
Location: Aboard the Enterprise

C allocate and initialize in same statement

Post 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
USS Enterprise NCC-1701,
The Final Frontier,
Space,
The Universe

Live Long And Prosper

Slava Ukraini!
Слава Україні!
Octocontrabass
Member
Member
Posts: 5512
Joined: Mon Mar 25, 2013 7:01 pm

Re: C allocate and initialize in same statement

Post 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.
User avatar
iansjack
Member
Member
Posts: 4685
Joined: Sat Mar 31, 2012 3:07 am
Location: Chichester, UK

Re: C allocate and initialize in same statement

Post 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?
Post Reply