指向整数指针数组的双指针;返回int&

时间:2014-02-10 23:37:14

标签: c++ arrays pointers resizable

所以我做了这个类项目的变种。 班级项目最初是这样的:

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)

2 个答案:

答案 0 :(得分:1)

第二部分**(array + index)无效,因为您可能没有为第二维分配内存。

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

但是,如果未初始化此指针,则会出现分段错误。

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

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

答案 1 :(得分:0)

Olaf是正确的,也可以添加第一部分func返回int&amp;引用现有变量,所以它是正确的。如果func为returnin int *,指针/地址为int

,则会产生错误
相关问题