如何在 C++ 中的动态分配数组中正确插入和显示数据?
我在尝试正确显示正确的内存地址时遇到了麻烦,因此我不知道在哪个内存地址中输入数据。
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << p << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << *p << " " << p << endl;
p++;
}
}
以下是输入数据时的输出:
以下是显示它们时的输出:
我担心的是输入数据时它不会输出正确的内存地址。
但是当显示它们时,显示正确的内存地址似乎没有问题。
I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data.
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << p << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << *p << " " << p << endl;
p++;
}
}
Here is the output when inputting data:
Here is the output when displaying them:
My concern is it doesn't output the correct memory address when inputting data.
But when displaying them it seems to have no problem displaying the correct memory address.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的输入循环在每次迭代时按原样显示
p
指针(即数组的基地址)。它不会在每次迭代时调整指针,这与输出循环不同。您还泄漏了数组,因为当您使用完它后,您没有
delete[]
'它。试试这个:
或者:
Your input loop is displaying the
p
pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does.You are also leaking the array, as you are not
delete[]
'ing it when you are done using it.Try this instead:
Alternatively: