这真的很奇怪
考虑以下两个代码:-
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
*ptr[i]=a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
AND
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
*ptr[3]=a[3];
*ptr[4]=a[4];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
cout<<*(ptr[3])<<endl;
cout<<*(ptr[4])<<endl;
}
第一个给出运行时错误,而第二个给出1、2、3、4、5输出,我找不到这两个代码之间的差异,谁能帮助我找到差异。
答案 0 :(得分:0)
我都遇到了运行时错误。 使用下面的指针变量进行重新编码的结果。
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
for(int i = 0; i < 5; i++)
{
ptr[i]=&a[i];
}
for(int i = 0; i < 5; i++)
{
cout<<*(ptr[i]);
}
}
答案 1 :(得分:0)
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
}
上面的代码运行正常,并提供输出1、2 但是
#include <iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5};
int* ptr[5];
*ptr[0]=a[0];
*ptr[1]=a[1];
*ptr[2]=a[2];
cout<<*(ptr[0])<<endl;
cout<<*(ptr[1])<<endl;
cout<<*(ptr[2])<<endl;
}
此代码在codeblocks(gcc)上给出了运行时错误,我只是更加困惑
答案 2 :(得分:0)
已经确定
*ptr[0] = a[0];
具有未分配的指针是未定义的行为。
解决方案
ptr[0] = &a[0];
也已经给出。此方法有效,但受到限制,因为现在ptr
数组已绑定到a
,而您并非总是想要这样。在这种情况下,您可能想要
ptr[0] = new int(a[0]);
这将使用a
中的值初始化数组,但使其保持独立。但是,这引入了手动内存管理,这在更复杂的代码(内存泄漏,双重释放,指针悬空)中可能会变得棘手,因此类似C ++的解决方案将是(假设指针指向的对象比整数更有趣),因为现在似乎不需要指针。)
#include <memory>
#include <vector>
#include <iostream>
int main() {
int a[]={1,2,3,4,5};
std::vector<std::unique_ptr<int>> ptrs;
for(auto i: a)
{
ptrs.emplace_back(std::make_unique<int>(i));
}
for(auto& i: ptrs)
{
std::cout << *i;
}
}