开发者

Initialize array variable in structure [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help 开发者_运维百科clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜