Initialize array variable in structure [closed]
I ended up doing like this,
struct init
{
CHAR Name[65];
};
void main()
{
init i;
char* _Name = "Name";
int _int = 0;
while (_Name[_int] != NULL)
{
i.Name[_int] = _Name[_int];
_int++;
}
}
Give your structure a constructor:
struct init
{
char Name[65];
init( const char * s ) {
strcpy( Name, s );
}
};
Now you can say:
init it( "fred" );
Even without a constructor, you can initialise it:
init it = { "fred" };
In C++, a struct can have a constructor, just like a class. Move the initialization code to the constructor. Also consider using a std::string instead of the char array.
struct init
{
std::string name;
init (const std::string &n) : name (n)
{
}
};
You could also use strcpy() to copy your string data into the char array.
strcpy(i.Name, "Name");
精彩评论