Home > Enterprise >  Pointer to arrays
Pointer to arrays

Time:12-27

Could anyone tell me why the second and the last receive compile-time errors?

void test(){
    
    int array[10]{};

    int (*i) [10] = &array; // works
    int (*j) [10] = array;  // does not work
    int *k = array;     // works
    int *l = new int[10](); // works
    int (*m) [10] = new int[10]();      // does not work

    exit(0);
}

I'm not sure why the second does not work without the ampersand since array and &array refer to the same address. For the last, I think it's because it can't tell we're dynamically allocating an array specifically, but I'd like this confirmed.

CodePudding user response:

I'm not sure why the second does not work without the ampersand since array and &array refer to the same address. int (*j) [10] = array;

array decays to int* not int (*)[10] in several contexts. So even though the value of array and &array is same the types are different. The type of array before decaying is int [10] which decays to int* while the type of &array is int (*)[10].

So the error is telling you that we cannot initialize a int(*)[10](type on the left hand side) with an int*(type on the right hand side after decay).

error: cannot convert ‘int*’ to ‘int (*)[10]’ in initialization

Similarly in the last case int (*m) [10] = new int[10]() the type on the right hand side is int* which cannot be used to intialize the type on the left hand side(int (*)[10]).

  •  Tags:  
  • c
  • Related