简体   繁体   中英

How can we initialize the structure?

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.

If you use c++ you can define a constructor, observe:

struct XYX {
   double a, b;

   XYX() { a=0; b=0; }
}

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.

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.

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.

除了xtofl的答案外,请注意,如果您想对数组进行零初始化,那么您要做的就是编写

XYZ abcd[10] = {};

你也可以用memset函数初始化

memset(&abcd[index], 0, sizeof(XYZ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM