如何将字符数组复制到结构的成员?

时间:2011-06-19 21:56:10

标签: c++ arrays

我有这样的事情:

struct cd { char name; cd *next;}

// some code...

int main(){
char title[100];

// some code...

cd *p =new cd;
p->name=title;

如何将数组title复制到p->name

2 个答案:

答案 0 :(得分:5)

如果你使用std::string,这很容易:

struct cd { std::string name; cd *next; };

int main() {
    // blah
    p->name = title;
}

但你可以做得更好。在C ++中,您可以使用构造函数初始化对象:

struct cd {
    cd(std::string newname) : name(newname), next() {}

    std::string name;
    cd *next;
};

int main() {
    // blah
    cd p(title); // initializes a new cd with title as the name
}

如果构造函数不合需要,可以使用聚合初始化:

struct cd {
    std::string name;
    cd *next;
};

int main() {
    // blah
    cd p = { title, NULL }; // initializes a new cd with title as the name
                            // and next as a null pointer
}

答案 1 :(得分:1)

在你的结构中,你需要一个char指针,而不是一个char:

struct cd {
    char * name;
    cd *next;
}

所以,你的最终代码将成为:

int main(int argc, char * argv[]) {
    char title[256];

    // code

    struct cd * p = new cd;
    p->name = new char[256];
    strcpy(p->name, title);
}

请注意,这是纯 C (除了新的,可以用malloc()替换,而不是C ++。

相关问题