Point to specific rows of 2-D arrays

180 Views Asked by At

I wrote the following code to point to first row of a 2-dimensional array. However, when I do

arrayPtr = & array[0];

I end up getting

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

 arrayPtr = & array[0];

My program is:

#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;
}

Can someone help me understand as to where am I going wrong?

3

There are 3 best solutions below

4
On BEST ANSWER

Instead of arrayPtr = & array[0], you can write

 arrayPtr = array[0];

to make use of array decay property.

Related,

  • Quoting C11, chapter §6.3.2.1, Lvalues, arrays, and function designators

    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. [...]

  • Quoting C++14, chapter §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.

    and, for chapter 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.

So, while used as the RHS operand of the assignment operator, array[0] decays to the pointer to the first element of the array, i.e, produces a type double* which is the same as the LHS.

Otherwise, the use of & operator prevents the array decay for array[0] which is an array of type double [1].

Thus, &array[0] returns a type which is a pointer to an array of double [1], or, double (*) [1] which is not compatible with the type of the variable supplied in LHS of the assignment, a double *.

0
On

In your code:

  • array is of type double (*)[1];
  • array[0] is of type double[1]
  • &array[0] (this equals to array) is of type double (*)[1] (i.e. pointer to double[1])

Note 1: T[] can decay to T*. So in your example double[] can decay to double *.

Note 2: a[b] == *(a + b), so in your example &array[0] equals to & (*(array + 0)) which is simplified to array itself.

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

arrayPtr has the type

POINTER (DOUBLE)

while array has the type

POINTER(POINTER(DOUBLE))

&array[0] has the type

POINTER(POINTER(DOUBLE))

You try to assign

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

The correct way to do it is

arrayPtr = array[0];

or

arrayPtr = *array;