该指针冲突的原因是什么?

What is the reason for this pointer conflicts?

本文关键字:是什么 指针 冲突      更新时间:2023-10-16

也许我只是让事情有些困惑。但是请考虑此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;
}
相关文章: