Why can't we use double pointer to represent two dimensional arrays?

前端 未结 5 989
我在风中等你
我在风中等你 2020-11-22 02:23

Why can\'t we use double pointer to represent two dimensional arrays?

arr[2][5] = {\"hello\",\"hai\"};
**ptr = arr;

Here why doesn\'t the d

5条回答
  •  無奈伤痛
    2020-11-22 02:55

    Let's start by talking about legal code. What you've written (assuming a char in front of each declaration) won't compile, for several reasons: you have too many initializers (six char's for arr[0], and its size is 5), and of course, char** p doesn't have a type compatible with char arr[2][5]. Correcting for those problems, we get:

    char arr[2][6] = { "hello", "hai" };
    char (*p)[6] = arr;
    

    Without any double pointer. If you want to access single characters in the above, you need to specify the element from which they come:

    char* pc = *arr;
    

    would work, if you wanted to access characters from the first element in arr.

    C++ doesn't have two dimensional arrays. The first definition above defines an array[2] or array[6] of char. The implicite array to pointer conversion results in pointer to array[6] of char. After that, of course, there is no array to pointer conversion, because you no longer have an array.

提交回复
热议问题