Cannot cast array to pointer

前端 未结 8 968
陌清茗
陌清茗 2020-12-14 23:41

I have the following source:

#include 
using namespace std;

void main(int j)
{
    char arr[10][10];
    char** ptr;
    ptr = arr;
}
         


        
8条回答
  •  时光取名叫无心
    2020-12-14 23:59

    The error exactly tells you whats wrong a double dimensional array can be assigned to an pointer to array not an double pointer. So what you need is:

    char (*ptr)[10] = arr; 
    

    What am I doing wrong?

    First things first
    Arrays are not pointers!! but they act sometimes like pointers.

    The rule is:

    An expression with array type (which could be an array name) converts to a pointer anytime an array type is not legal, but a pointer type is.

    So if you have a single dimensional array:

    char arr[10];
    

    Then arr decays to address of the zeroth element it has the type char *. Hence:

    char *ptr = arr;
    

    But if you have an 2 dimensional array which is essentially an array of arrays.

     char arr[10][10];
    

    Then arr decays to the pointer to an array of 10 characters.

    So, In order to assign arr to something, you will need that something to match the type, which is pointer to an array of characters.
    Hence:

    char (*ptr)[10] = arr; 
    

提交回复
热议问题