我真的可以用圆括号初始化数组吗?
有时,我会在程序代码的一处出现拼写错误:
int a = 10;
char* b = new char(a);
错误很明显:我写的是 () 而不是 []。奇怪的是......代码编译正常,它在调试器中运行正常。但是在执行这些行的函数后,在调试器之外编译的 .exe 崩溃了。
第二行代码真的合法吗?如果是的话,这对编译器意味着什么?
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.
Is second line of code really legitimate? And if it is, what does it mean to compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它是一个数值为
a
的单个字符,在本例中为10
。你知道,指针不仅仅指向数组。It's a single char with the numerical value of
a
, in this case10
. Pointers don't only point to arrays, y'know.您正在分配一个单个
char
并为其分配来自a
的值。它根本不分配数组。这与在任何其他类型的 new 表达式中调用构造函数相同:
You're allocating a single
char
and assigning it a value froma
. It's not allocating an array at all.It's the same as calling the constructor in a
new
expression for any other type:char t(a)
创建一个本地字符,并初始化为a
的值。new char (a)
创建一个动态分配的 char,并初始化为a
的值。char t(a)
creates a local char initialized to the value ofa
.new char (a)
creates a dynamically allocated char initialized to the value ofa
.