Reputation:
Suppose there is a structure such as:
struct XYZ
{
double a;
double b;
}
Now we make an object of it
struct XYZ abcd[10];
and now I am filling this array.
I have to initialize this array because I call this in a loop and it overwrites the previous values.
If it overwrites the previous 5 values by 4 new values then still the 5th one is still there in the array which results in the wrong output.
Upvotes: 0
Views: 467
Reputation: 32635
In addition to xtofl's answer, note, that if you want to zero-initialize the array, all you have to do is write
XYZ abcd[10] = {};
Upvotes: 0
Reputation: 41509
Initializing a struct is easily done by enumerating it's member values inside curly braces. Beware, though, 'cause if a member is omitted from the enumeration, it will be regarded as zero.
struct A { int a_, b_; };
A a = { 1, 2 };
A b = { 1 }; // will result in a_=1 and b_=0
A as [] = { {1,2}, {1,3}, {2,5} };
Strangely enough, this also works for the public members of an "aggregate" class. It's to be discouraged, though, since this way your class will lose it's ability to do the necessary things at construction time, effectively reducing it to a struct.
Upvotes: 3
Reputation: 393
Also you can initialize with memset function
memset(&abcd[index], 0, sizeof(XYZ));
Upvotes: -3
Reputation: 35450
If your question is how to initialize the array elements then @cemkalyoncu answer will help you.
If it over rites the previous 5 values by 4 new values then still the 5th one is still there in the array which in result gives wrong output.
For this case it is better you go for vector. You can remove the unwanted elements from the vector to make sure that it does not contain the wrong values.
In this case, remove 5th element from vector if you no longer use.
Upvotes: 1
Reputation: 20163
for (int i=0; i<10; ++i)
{
abcd[i].a = 0.0;
abcd[i].b = 0.0;
}
Of course, if some of the slots haven't been filled with meaningful data you probably shouldn't be looking at them in the first place.
Upvotes: 1
Reputation: 14593
If you use c++ you can define a constructor, observe:
struct XYX {
double a, b;
XYX() { a=0; b=0; }
}
Upvotes: 3