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

How do I copy an array of characters to a member of a struct?

本文关键字:结构 成员 复制 字符 数组      更新时间:2023-10-16

我有这样的东西:

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

如果使用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
}

在结构中,您需要一个字符指针,而不是一个字符:

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++。