动态 allcocation 对象和 int c++
你好我有一个疑问下面的代码是如何工作的?
#include <iostream>
using namespace std;
int main()
{
int* arr = new int;
arr[0] = 94;
arr[1] = 4;
cout << arr[0] << endl;
}
为什么这会显示错误我应该做什么
#include <iostream>
using namespace std;
struct test
{
int data;
};
int main()
{
test* arr = new test;
arr[0] -> data= 4;
arr[1] -> data= 42;
cout << arr[0]->data << endl;
}
hello I have a doubt how does the code below works??
#include <iostream>
using namespace std;
int main()
{
int* arr = new int;
arr[0] = 94;
arr[1] = 4;
cout << arr[0] << endl;
}
and why does this shows me a error what should I do
#include <iostream>
using namespace std;
struct test
{
int data;
};
int main()
{
test* arr = new test;
arr[0] -> data= 4;
arr[1] -> data= 42;
cout << arr[0]->data << endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的代码中:
Int 上述代码,
arr
是指向单个int
的指针,因此您可以使用以下任一方式访问该int
:。 .但是 arr1 不起作用,因为没有分配了足够的内存 大批。
要解决此问题,您必须为 arr: .. 分配更多内存并
更改 arr: 的大小,
但是当 arr 具有大量元素时,所有这些都会变得计算昂贵且耗时。因此,我建议使用
C++
的std::vector
:使用
std::vector
的第二个程序:有关
的更多信息>std::vector
,点击此处。另外,请考虑不在代码中使用以下行:
..因为它被认为是不好的做法。有关这方面的更多信息,请查看 为什么是“using namespace std”被认为是不好的做法。
In your code:
Int the above code,
arr
is a pointer to a singleint
, so you can access that oneint
using either:..but arr1 won't work as there is not enough memory allocated for the array.
To fix this, you must allocate more memory for arr:
..and to change the size of arr:
But all of this gets computationally expensive and time-consuming when
arr
has a huge number of elements. So I recommend usingC++
'sstd::vector
:Your 2'nd program using
std::vector
:For more info on
std::vector
, click here.Also, consider not using the following line in your code:
..as it's considered as bad practice. For more info on this, look up to why is "using namespace std" considered as bad practice.