c++c++11variable-assignmentaddressof

Point to specific rows of 2-D arrays


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?


Solution

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

     arrayPtr = array[0];
    

    to make use of array decay property.

    Related,

    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 *.