如何将字符数组复制到结构的成员中
How do I copy an array of characters to a member of a struct?
我有这样的东西:
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++。
相关文章:
- 具有结构成员char数组的sscanf
- 仅使用结构名称访问结构成员
- 使用 structType*& 赋给结构成员
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 是否可以将结构数组别名为结构成员数组?
- 结构成员在访问时被清除
- 如何指示结构成员没有锯齿?
- 为什么继承的结构成员在联合中无法访问?
- 尝试在 qml 中访问结构成员的 QList
- C++/CLI -- 访问结构成员
- 调用在类中声明的结构成员
- 对结构成员的临时绑定引用
- 无法使用 strcpy 将字符串复制到静态结构成员
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- 填充模板化结构类型的结构成员
- C/C++intellisense 0.26.1不显示结构成员列表
- 在源文件中创建具有结构成员的结构
- 如何访问结构成员作为指针