From Java I'm used that I can do this:
public class SomeClass {
public int field1;
}
SomeClass[] data = new SomeClass[10];
for (int i = 0; i < 10; i++) {
data[i] = new SomeClass();
SomeClass d = data[i];
d.field1 = 10;
}
for (int i = 0; i < 10; i++) {
SomeClass d = data[i];
System.out.println("Value of data [" + i + "] is [" + d.field1 + "]");
}
And this will work fine, printing:
Value of data [0] is [10]
Value of data [1] is [10]
... etc
So in Java you first create the Array, which has by default all null values, and then in the first loop I create a new SomeClass and assign it to a slot in the array. If you don't do this you get a NullPointerException.
All fine.
The question: I try to do the same in C++. I have one failing and one working example. But I am unsure why it works (or does not work, depending what example you pick). Can anyone elaborate?
First, the failing code:
int main(int argc, char **argv) {
MyClass data[10];
for (int y = 0; y < 10; y++) {
MyClass d = data[y];
cout << "INITIALLY (garbage): [" << d.field1 << ", " << d.field2 << "] " << endl;
// assign values
d.field1 = 2;
d.field2 = 3;
}
// print out data of first 10
cout << "Printing out data after initialization" << endl;
for (int y = 0; y < 10; y++) {
MyClass d = data[y];
cout << "[" << d.field1 << ", " << d.field2 << "] " << endl;
}
}
So If i understand correctly, according to this StackOverflow question I can create an array of a Struct like I do in the above code.
What I noticed is that if I do not use:
MyClass d = data[y];
d.field1 = 2;
d.field2 = 3;
But instead I do:
data[y].field1 = 2;
data[y].field2 = 3;
It does work.
However, if I insist on using a separate value, I can still make it work by doing this:
MyClass * d = &data[y];
d->field1 = 2;
d->field2 = 3;
I do not change anything in printing the output. And the above works.
So, something clearly is different when using a pointer to data[y]. I cannot found a clear answer on this though. Anyone able to explain why?
If this question is a duplicate, sorry for that, I could not find a real answer on the "why" part. Code snippets are not always enough for me ;)
PPS: I am aware that I am not allocating this array in the heap. Bonus points for touching that subject to compare to :)