c++ - 在使用指针算术时为指针数组赋值给我错误

标签 c++ pointers

当我做这个指针算术时,它总是给我一个错误


int main()
{
    const int rowSize=40;
    int* unique=nullptr;

    int arr[rowSize]={1,1,11,31,21,22,2,2,3,32,31,3,4,34,45,5,55,5,55,5,6,46,64,6,7,27,74,7,7,7,7,11,11,11,11,11,1,2,13,4};
    int amount=0;

    for (int count=0; count<rowSize; count++)
    {
        if (arr[count]!=arr[count+1])
        {
            amount++;
        }
    }
    unique= new int[amount];
    for (int count=0; count<rowSize-1; count++)
    {
        if (arr[count]!=arr[count+1])
        {
            *unique=arr[count];
            unique++;
        }
    }

    for (int count=0; count<20; count++)
    {
        cout<<unique[count]<<" ";
    }
    cout<<endl;
    delete [] unique;
    unique=nullptr;
    return 0;
}


每次我做这个指针算术,*unique=arr[count] 和 unique++,它总是在最后给我一个时髦的输出。

最佳答案

更改 new[] 返回的指针的值运算符(operator)是极其危险的,而且从来都不是真正正确的编码方式。这是因为,在某些时候,您需要使用 delete[] 释放该内存。 '调用'到 new[] 的地址给你。

在您的情况下,调用您的模块 uniqueArr函数得到一个返回值,它将 不再 (在大多数情况下)是 delete[] 的正确地址打电话,那将失败。

使用 [] 会好得多指针上的运算符,使用您在适当时增加的索引值(您当前增加指针的位置)。像这样的东西:

//...
    int* unique = new int[amount];
    size_t uIndex = 0;

    for (int count=0; count<rowSize-1; count++)
    {
        if (arr[count]!=arr[count+1])
        {
            unique[uIndex] = arr[count]; // The [] works fine with a 'new[]' pointer!
            uIndex++; // You could even include this POST-increment inside the [], above!
        }
    }
//... You can now 're-use' "unique" as it will still be the original address.
//...

这样,函数返回的值与new[]的返回值不变。运算符,并且对任何后续的 delete[] 都有效手术。

随时要求进一步澄清和/或解释。

编辑:另一种方法(尽管恕我直言不好)是第二个 int*保存 unique 值的指针,然后恢复 unique在“重新使用”它之前(在第二个循环中,或在调用 delete[] 之前)。

关于c++ - 在使用指针算术时为指针数组赋值给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61614703/

相关文章:

c++ - Boost日志宏解释

c++ - 如何在C++中绑定(bind)变量

c - free()之前是否需要检查指针是否为空

c - sizeof 运算符在 C 中接受哪些参数?

c++ - 托管代码中使用的 STL vector

c++ - 获取给定数字集中具有相同数字频率的组数

c - 任何人都可以向我解释以下内容

c - C 中的子串

memory - 有人可以解释 Marshal.StructureToPtr

c++ - 错误 LNK1104 : cannot open file 'Debug\MyProjectLib.lib'