简体   繁体   English

我可以用圆括号初始化数组吗?

[英]Can I really initialize an array with round brackets?

Occasionaly, I've made a typo in one place of code of my program: 偶尔,我在我的程序代码的一个地方写了一个拼写错误:

int a = 10;  
char* b = new char(a);

Error is obvious: I've written () instead of []. 错误是显而易见的:我写了()而不是[]。 The strange thing is... code compiled ok, it ran in debugger ok. 奇怪的是...代码编译好了,它在调试器中运行确定。 But compiled .exe outside of debugger crashed a moment after function with these lines was executed. 但是在执行这些行的函数之后,在调试器之外编译的.exe崩溃了一会儿。

Is second line of code really legitimate? 第二行代码真的合法吗? And if it is, what does it mean to compiler? 如果是,那对编译器意味着什么?

It's a single char with the numerical value of a , in this case 10 . 这是一个单个字符与的数值a ,在这种情况下10 Pointers don't only point to arrays, y'know. 你知道,指针不只指向数组。

You're allocating a single char and assigning it a value from a . 你分配一个单一的 char并赋予它从一个值a It's not allocating an array at all. 它根本没有分配数组。

It's the same as calling the constructor in a new expression for any other type: 它与在任何其他类型的new表达式中调用构造函数相同:

std::string* s = new std::string("foo");
int* i = new int(10);
std::vector<std::string>* v = new std::vector<std::string>(5, "foo");

char t(a) creates a local char initialized to the value of a . char t(a)创建一个初始化为a值的本地char。
new char (a) creates a dynamically allocated char initialized to the value of a . new char (a)产生初始化的值的动态分配的炭a

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

相关问题 如何用数组初始化结构数组? - How can I initialize an array of struct with array? 如何使用1个非常大的数组快速初始化 - How to fast initialize with 1 really big array 您可以使用大括号在C ++中的return语句中初始化数组吗? - Can you initialize an array in a return statement in C++ using curly brackets? 如何初始化对象数组? - How can I initialize an array of objects? 为什么我可以使用大括号用另一个枚举类的值来初始化一个枚举类? - Why can I use curly brackets to initialize one enum class with a value from another enum class? 为什么我可以从{}初始化常规数组,而不是std :: array - Why can I initialize a regular array from {}, but not a std::array 如何从多维缓冲区初始化 NumPy 数组? - How can I initialize a NumPy array from a multidimensional buffer? C ++中的对象的多维数组,我无法初始化它! - Multidimensional array of object in C++ , I can not initialize it! 我可以从向量数组初始化一个 std::tuple 吗? - can I initialize an std::tuple from a vector array? 如何使用float数组中的数据初始化cv :: Mat - How can I initialize a cv::Mat with data from a float array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM