[英]What does new char(size) mean in C++?
While allocating a buffer via new
(in C++) I mistakenly wrote: 通过
new
(在C ++中)分配缓冲区时,我错误地写道:
int size = 1024 * 1024;
char *buf = new char(size);
instead of the normal syntax 而不是普通的语法
char *buf = new char[size];
However the code did get compiled and led to strange crashes when using this buf
variable. 但是,使用此
buf
变量时,代码确实被编译并导致奇怪的崩溃。 Apparently it seems that a buffer of eight bytes was allocated. 显然,分配了八个字节的缓冲区。
I would like to know the meaning of new char(size)
. 我想知道
new char(size)
的含义。
char *buf = new char(size);
It allocates only sizeof(char)
bytes and initializes it with size
— loosely equivalent to this: 它仅分配
sizeof(char)
个字节,并使用size
对其进行初始化- 大致等效于此:
char *__internal_buf = new char; //1 byte only
*__internal_buf = size; //or static_cast<char>(size);
char *buf = __internal_buf;
It is the same difference as in these two: 这与这两个相同:
char x(65); //y is single element initialized to be 'A'. as 65 is 'A'
char y[65]; //y is an array of size 65
Hope that helps. 希望能有所帮助。
It means you allocate memory for a single char
and initialize it with the integer size
. 这意味着您为单个
char
分配内存,并使用整数size
对其进行初始化。 In your case, size
doesn't fit into a char
. 就您而言,
size
不适合char
。 If the char
happens to be signed, then the integer size
is being converted into a char
, but the results are implementation-defined. 如果
char
恰好是带符号的,则整数size
将转换为char
,但是结果是实现定义的。 If the char
is unsigned
, then the int
wraps around the maximum value represented by the char
(typically 255). 如果
char
是unsigned
,则int
包装char
表示的最大值(通常为255)。
A similar syntax exists also for non-pointers: 非指针也存在类似的语法:
int x(10); // initialize x with 10
or 要么
char c('a'); // initializes c with 'a'
Null, but here's a better example: 空,但这是一个更好的示例:
#include <iostream>
using namespace std;
int main() {
int size = 'A';
char *buf = new char(size);
cout << *buf;
}
Prints out A 打印出A
Reason for NULL: 1024*1024 = 0x100000. NULL的原因:1024 * 1024 = 0x100000。 The last byte goes in the char.
最后一个字节进入char。 Char is Null.
字符为空。 Least efficient null terminated string I've seen in a while, in fact.
实际上,我在一段时间内看到的效率最低的null终止字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.