C++ 动态分配的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/958549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically allocated char
提问by Johannes Schaub - litb
int main()
{
char *second= new char("hello");
char *first="hi";
char third[]="new";
}
I am new to c++ and don't really understand how char works, why the first one give a compiler error, and what are the differences of those 3 way of declaration , the strength and benefits of declaring it in a particular way.
我是 C++ 新手,并不真正了解 char 是如何工作的,为什么第一个会出现编译器错误,以及这 3 种声明方式的区别,以特定方式声明它的强度和好处。
Thanks
谢谢
Hmm, as someone mentions that the second form is read only, why could I Change it. suppose I have the code below
嗯,正如有人提到第二种形式是只读的,我为什么要改变它。假设我有下面的代码
int main()
{
char *second= new char("hello");
char *first="hi";
char third[]="new";
first="world";
}
code like above will still execute, why is it so? , then which form is better if I want to read an input but don't know the size of the string?
上面的代码仍然会执行,为什么会这样?,那么如果我想读取输入但不知道字符串的大小,哪种形式更好?
回答by Johannes Schaub - litb
Know that
我知道
"abc"
allocates static storage somewhere, which lasts the whole program lifetime. You cannot write to that storage, so C++ gives it the type char const[N]
(an array of N constant characters). Now, the following makes a pointer point to that storage
在某个地方分配静态存储,这会持续整个程序生命周期。您无法写入该存储,因此 C++ 为其提供类型char const[N]
(N 个常量字符的数组)。现在,以下内容使指针指向该存储
char *first = "hi";
Since that drops a const
, that way of initializing the pointer is deprecated. That it works at all is just to keep backward compatibility with C, where a string literal does not have a const type (but is still read only). Prefer the following instead
由于这会删除 a const
,因此不推荐使用这种初始化指针的方式。它完全有效只是为了保持与 C 的向后兼容性,其中字符串文字没有 const 类型(但仍然是只读的)。更喜欢以下内容
char const *first = "hi";
In constrast, the last way you have shown copies the string literal's content to an array, which will be writable, and be sized so the string literal just fits into it.
相比之下,您所展示的最后一种方式是将字符串文字的内容复制到一个数组中,该数组将是可写的,并调整大小以便字符串文字正好适合它。
char third[] = "new";
If you do that in a function, then as all variables, that array will be cleaned up when you leave its scope. Now, the first way you have shown is different. It creates a character dynamically. You could have initialized it like this
如果您在函数中执行此操作,那么作为所有变量,当您离开其作用域时,该数组将被清除。现在,您展示的第一种方式是不同的。它动态地创建一个角色。你可以像这样初始化它
char *c = new char('A');
And since that happens dynamically, you need to tell the compiler explicitly when it should free the memory
由于这是动态发生的,您需要明确告诉编译器何时应该释放内存
delete c;
But you cannot initialize the character with a string literal. What you probably had in mind is creating storage dynamically, initialized with the string literal. That's not possible using new
. The only form of initializing a dynamic array is to zero it out, but you cannot directly-initialize with the content of a string literal or another array. For this form of using new
, there is rarely a need to do that directly. If you want, you can do it by creating a dynamic array of the right size, and then copy bytes from the string literal to that buffer
但是您不能用字符串文字初始化字符。您可能想到的是动态创建存储,并使用字符串文字进行初始化。使用new
. 初始化动态数组的唯一形式是将其清零,但您不能直接使用字符串文字或其他数组的内容进行初始化。对于这种形式的 using new
,很少需要直接执行此操作。如果需要,您可以创建一个大小合适的动态数组,然后将字节从字符串文字复制到该缓冲区
char *c = new char[sizeof "hello"]; // sizeof "hello" will give 6
std::strcpy(c, "hello");
delete[] c; // delete[] is for deleting dynamic arrays
Remember that this is quite low-level, and i recommend you to use strings
请记住,这是相当低级的,我建议您使用字符串
std::string s = "hello"; // s.size() gives you its size
It completely manages memory for you. Concatenation, indexing and that stuff is available too.
它完全为您管理内存。连接、索引和那些东西也可用。
回答by elcuco
Lets try to explain in code:
让我们试着用代码来解释:
// your code
char *first="hi";
// this is the memory location of the string, assigned by the compiler
// sizeof(first) == sizeof(char*) == 4 (usually, lets not get into this right now)
char *first = 0x12345;
// your code
char third[]="new";
// means, the following:
char third[4];
third[0] = 0x6E; // ascii code of 'n'
third[1] = 0x65; // ascii code of 'e'
third[2] = 0x77; // ascii code of 'w'
third[3] = 0x00; // strings in C end with NULL
// note that sizeof(third) is still sizeof(char*), but this
// time you statically allocated sizeof(char)*4 for the whole array
More reading for you:
为您提供更多阅读: