4

I have the following code

char str[] = "some string"; // legal
char const* str2 = str;     // legal
char const** str3 = &str2;  // legal
char const** str4 = &str;   // illegal (error: cannot convert 'char (*)[12]' to 'const char (*)[]' in initialization )

Why the last one is not compiled? What is the type of &str?

user14416
  • 2,922
  • 5
  • 40
  • 67

2 Answers2

7

Since str is an array, the type of &str is a "pointer to array of 12 const char". The valid declaration would be:

char const (*str4)[12] = &str;

The declaration of str3 works fine because str2 is a "pointer to const char", not an array, initialized using array-to-pointer conversion. The same array-to-pointer conversion does not occur when you take the address of an array, as in the declaration of str4.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

Because of the number of de-referencings. (str[] or str*) -> data, str2 -> data, str3 -> pointer(str2) -> data, str4 -> pointer -> data. The number of * simbols tells you home many imes you need to dereference it to get to the data. Each time is jumping from address to address and only the last access is asctually data.

The right way would be:

char const* str4 = &str; //or
char const* str4 = str2;
emd
  • 740
  • 4
  • 12