简体   繁体   English

如何将字符串分配给 const char*?

[英]How can a string be assigned to a const char*?

How is it possible to assign a string (an array of chars, if I'm understanding this correctly) to a const char* ?怎么可能将一个字符串(一个字符数组,如果我理解正确的话)分配给一个const char* Any other pointer requires the new keyword followed by a type, but in this case the string is just assigned to a pointer.任何其他指针都需要new关键字后跟一个类型,但在这种情况下,字符串只是分配给一个指针。 The pointer is a memory address, not an array of chars, but somehow it accepts the array of chars as a value.指针是一个内存地址,而不是一个字符数组,但它以某种方式接受字符数组作为一个值。

(I really have tried finding an answer to this, but as I'm beginner I might have missed it, apologies if that's the case.) (我真的尝试过找到答案,但作为初学者,我可能已经错过了,如果是这种情况,我深表歉意。)

Arrays can be implicitly converted to pointers to their first elements.数组可以隐式转换为指向其第一个元素的指针。

Most (but not all) operations on arrays perform this conversion, so arrays and pointers are often confused with each other.大多数(但不是全部)对数组的操作都会执行这种转换,因此数组和指针经常相互混淆。 Good job figuring out the difference early on.很好地尽早找出差异。


Any other pointer requires the new keyword任何其他指针都需要new关键字

Not true, consider this:不正确,请考虑:

int x;
int *y = &x;

While you should know what they do, the manual use of new and delete is discouraged in modern C++, unless you're writing your own container or smart pointer.虽然您应该知道它们的作用,但在现代 C++ 中不鼓励手动使用newdelete ,除非您正在编写自己的容器或智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM