所以我对这个类(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/