指向二维数组的特定行

Point to specific rows of 2-D arrays

我写了下面的代码来指向二维数组的第一行。然而,当我这样做时

arrayPtr = & array[0];

我最终得到

error: cannot convert double (*)[1] to double* in assignment

 arrayPtr = & array[0];

我的程序是:

#include <iostream>
    
int main(int argc, char **argv) 
{       
    double array[2][1];

    array[0][1] = 1.0;
    array[1][1] = 2.0;
    
    double* arrayPtr;
    arrayPtr = &array[0];
    
    return 0;
}

有人可以帮助我了解我哪里出错了吗?

而不是arrayPtr = & array[0],你可以写

 arrayPtr = array[0];

利用数组衰减属性。

相关,

  • 引用 C11,章节 §6.3.2.1,左值、数组和函数指示符

    Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

  • 引用 C++14,章节 §5.3.3

    The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the operand of sizeof.

    并且,对于章节 4.2

    An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

因此,当用作赋值运算符的 RHS 操作数时,array[0] 衰减为指向数组第一个元素的指针,即产生一个类型 double* 与LHS.

否则,使用 & 运算符可防止 array[0] 的数组衰减,后者是 double [1] 类型的数组。

因此,&array[0] returns 是指向 double [1] 数组的指针的类型,或者 double (*) [1] 兼容 与分配的 LHS 中提供的变量类型,double *.

在您的代码中:

  • array 的类型是 double (*)[1];
  • array[0] 的类型是 double[1]
  • &array[0](这等于 array)属于 double (*)[1] 类型(即指向 double[1]

注1:T[]可以衰减到T*。所以在你的例子中 double[] 可以衰减到 double *.

注 2: a[b] == *(a + b),因此在您的示例中 &array[0] 等于 & (*(array + 0)) 已简化array 本身。

double array[2][1];
double* arrayPtr;
arrayPtr = & array[0];

arrayPtr 具有类型

POINTER (DOUBLE)

array 具有类型

POINTER(POINTER(DOUBLE))

&array[0] 具有类型

POINTER(POINTER(DOUBLE))

您尝试分配

POINTER (DOUBLE) <= POINTER(POINTER(DOUBLE))

正确的做法是

arrayPtr = array[0];

arrayPtr = *array;