该指针冲突的原因是什么?
What is the reason for this pointer conflicts?
也许我只是让事情有些困惑。但是请考虑此C 代码:
#include <iostream>
#include <list>
using namespace std;
void printArray(int *arr, int n)
{
for(int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
list<int*> arrays;
int times=20, v[9]={1,2,3,4,5,6,7,8,0};
arrays.push_back(v);
while(times--)
{
int *cur = arrays.front();
arrays.pop_front();
printArray(cur, 9);
int ta[9], tb[9];
for(int i=0; i<9; ++i)
{
ta[i] = *(cur+i)+1;
tb[i] = *(cur+i)-1;
}
arrays.push_back(&ta[0]);
arrays.push_back(&tb[0]);
}
return 0;
}
您可以看到,目的是用默认数组{1,2,3,4,5,6,7,8,0},存储(在 times iterations中)在int指针列表中,此数组的2个变体。
因此,在第一次迭代中,两个阵列{2,3,4,5,6,7,8,9,1}和{0,2,3,,5,6,7,-1}应该存储在列表中,因此,第一个3 printarray 应为:
1 2 3 4 5 6 7 8 0
2 3 4 5 6 7 8 9 1
0 1 2 3 4 5 6 7 -1
现在,发生的事情是第一个3 printarray 是:
1 2 3 4 5 6 7 8 0
2 3 4 5 6 7 8 9 1
2 3 4 5 6 7 8 9 1
我已经打印了 ta 和 tb 在每次迭代中,我知道真正被打印出来的是 1) 2)第一个TA的第一个TA, 3) TB的TB。但是我真的不知道这种行为的原因是什么,我的意思是,不是 ta 和 tb 新数组(独立于以前的迭代)?如果是这种情况,我的for只是为新数组位置分配值,那么它们为什么相互冲突?
问题很简单。
正如@quimnuss在评论中所述的那样, ta 和 tb 在某个时候进行了交易,因此,保存在列表中的指针将指向与这些指示完全不同的东西被划分的阵列,导致该程序的行为。
此语句完全有意义,因为 ta 和 tb 是while循环的局部变量,因此它们的有效性在每个迭代完成时都会用尽。
我们可以通过在每次迭代中动态分配内存来解决此问题,例如:
int *ta = new int[9];
int *tb = new int[9];
由于此数组的范围不再本地循环。
最终代码:
#include <iostream>
#include <list>
using namespace std;
void printArray(int *arr, int n)
{
for(int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
list<int*> arrays;
int times=20;
int *v = new int[9];
for(int i=0; i<8; ++i)
v[i] = i+1;
v[8] = 0;
arrays.push_back(v);
while(times--)
{
int *cur = arrays.front();
arrays.pop_front();
printArray(cur, 9);
int *ta = new int[9];
int *tb = new int[9];
for(int i=0; i<9; ++i)
{
ta[i] = *(cur+i)+1;
tb[i] = *(cur+i)-1;
}
arrays.push_back(ta);
arrays.push_back(tb);
delete[] cur;
}
while(!arrays.empty())
{
int *p = arrays.front();
arrays.pop_front();
delete[] p;
}
return 0;
}
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++:Lambda 函数指针转换的用例是什么?
- C++关于指针和使用函数将它们启动到堆的行为究竟是什么?
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 为什么此指针值不能转换为整数的规则是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 以下与指针相关的代码的输出是什么?
- 指针类型类成员的动态强制转换的恒定性是什么?
- 指针算术规则中的"possibly-hypothetical"是什么意思?
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- "*&n"在双指针 C++ 中是什么意思?
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?
- 在接口中使用通用指针的原因/正确情况是什么
- 使用作为参数返回的指针的最佳做法是什么
- 在C++中有多个指向单个对象的指针的正确方法是什么?
- 键入擦除成员函数指针的"right"方法是什么?