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

发布于 2024-12-15 05:00:43 字数 217 浏览 3 评论 0原文

有时,我会在程序代码的一处出现拼写错误:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

じ违心 2024-12-22 05:00:43

它是一个数值为 a 的单个字符,在本例中为 10。你知道,指针不仅仅指向数组。

It's a single char with the numerical value of a, in this case 10. Pointers don't only point to arrays, y'know.

白昼 2024-12-22 05:00:43

您正在分配一个单个 char 并为其分配来自a 的值。它根本不分配数组。

这与在任何其他类型的 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");

You're allocating a single char and assigning it a value from 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:

std::string* s = new std::string("foo");
int* i = new int(10);
std::vector<std::string>* v = new std::vector<std::string>(5, "foo");
没有你我更好 2024-12-22 05:00:43

char t(a) 创建一个本地字符,并初始化为 a 的值。
new char (a) 创建一个动态分配的 char,并初始化为 a 的值。

char t(a) creates a local char initialized to the value of a.
new char (a) creates a dynamically allocated char initialized to the value of a.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文