c++ - 指向整数指针数组的双指针;返回整数&

标签 c++ arrays pointers resizable

所以我对这个类(class)项目做了一个变体。 类(class)项目本来是这样的:

int* array;
array = new int[size];

// int& method
return array[index];

为什么会这样? array[index] 返回的值不是地址,对吗? [] 取消引用指针?

--- 变体 --

int** array;
array = new int*[size];

int& RA::setget(int index)
{

    if ((index >= 0) && (index < capacity))
    {
        return **(array + index); // this part isn't working
    }
    else
        throw out_of_range("blah"); // forgot the () out_of_range(). needed to put text in the exception!!!
}

这不行,但不是一样的吗? int** 数组,所以我做 **(array+index)

最佳答案

第二部分 **(array + index) 不工作,因为你可能没有为第二个维度分配内存。

当你执行 *(array + index) 时,你会得到一个指向 int int* 的指针。当您现在再次取消引用 **(array + index) 时,您将获得该指针指向的值。

但是当这个指针没有被初始化时,你会得到一个段错误。

要使其工作,您必须初始化int* 数组

for (int i = 0; i < size; ++i)
    array[i] = new int[other_size];

关于c++ - 指向整数指针数组的双指针;返回整数&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21690169/

相关文章:

c++ - shared_ptr 的分配是否会破坏 `this` 指针

javascript - 如何使用 Array.from 使用 MIN MAX 生成范围

c++ - 将 3D 指针数组传递给函数

c++ - 将 y=x*x 舍入到最近的

c++ - OpenCV图像变换和透视变化

ios - 如何在 Swift 中按数组元素分组

javascript - 合并多个对象数组并平均重复值javascript

c++ - 对指针进行解引用并存储指向所指向数据的引用,然后获取引用的地址并对其进行指针算术运算。 C++

c - 此 C 代码中的负索引如何产生给定的输出?

c++ - 在 C++Builder 6 中使用自定义颜色