Why is this code giving an error ....... 'a' is a pointer to a pointer to a character and must store the address of 's' since s is a pointer to the first element of the array

#include<iostream> 
using namespace std;

int main()
{
    char s[] = "Hello";
    char **a = &s;  //Give compilation error
    cout<<a;
}

      

Since s is a pointer to the first element, I should be able to store its address in a pointer to a character pointer variable .. but it shows an error.

+3


source to share


2 answers


An expression &s

is a pointer to an object of type char[6]

, which is an array type s

.

On the other hand, a type char **

is a pointer type for a type object char *

. Types char[6]

and char *

are different types. Thus, pointer types are incompatible.

Your mistake is that you think that in this expression &s

the array notation is implicitly converted to a pointer to its first element. However, this assumption is incorrect.



It is more explicit in the C standard (6.3.2.1 Lvalues, arrays and function pointers) than in the C ++ standard

3 Except when it is the operand of a sizeof or unary operator and an operator or string literal used to initialize an array, an expression that is of type 'array of type is converted to an expression of type' a pointer to type pointing to the starting element of the object array and is not an lvalue. If the array object has a register storage class, the behavior is undefined.

+2


source


Using an array s

can cause the pointer to its first element to decay.



Using an s

optional pointer is equal to doing &s[0]

. This pointer will be of type char *

. The expression &s

is a pointer to an array and will be of type char (*)[6]

. This is completely different.

+3


source







All Articles