Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.
Use a[i] = new myClass() in your loop. This 0-argument constructor for class myClass will be generated by Java. Names of the classes in Java are written LikeThis by convention.
myStruct = (MyStruct*)calloc(1, sizeof(MyStruct)); should initialize all the values to zero, as does: myStruct = new MyStruct();
In our code we used to have something like this:
*(controller->bigstruct) = ( struct bigstruct ){ 0 };
This used to work great, and then we upgraded versions of GCC and suddenly started seeing stack overflows. Looking at the assembly, the old GCC code (2.x) was basically doing this:
memset(controller->bigstruct, 0, sizeof(struct bigstruct));
The new GCC (3.4.x) was doing this
struct bigstruct temp = { 0 }; controller->bigstruct = temp;
After reviewing the C99 spec, I could see why; C99 basically requires that anonymous structures exist on the stack. It's a good concept, but this structure was 4 Megabytes large, and only ever intended to exist on heap!
We've resorted to making our own 'initialize' function that explicitly sets the members, but that's ugly and a maintenance headache. I don't consider memset a proper solution, because I can't know that a bit-value of 0 is an appropriate zero value for the type ( nit-picking, I know, but there you are; I don't mind that the compiler does it, because it can know )
What is the "correct", or at least best, way to initialize a large structure like this?
To furthur clarify why I think memset isn't a solution: The rules of initialization of members not explicitly initialized are the same as static initialization, and are as follows: - If it has pointer type, it is initialized to a null pointer; - If it has arithmetic type, it is initialized to ( positive or unsigned ) zero; ...
'memset' will set the memory to bit-pattern zero, which isn't necessarily the same thing. Imagine a system that doesn't use IEEE floating point numbers. Unusual, but supported by C. The representation of 0.0 doesn't have to mean "all-bits zero", it could be anything convenient to the processor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With