Pointer initialization

When I type int * a = 10

it shows an error. But when I give char *b = "hello"

it doesn't show an error?

We cannot initialize values ​​directly to pointers, but how is this possible only in char

. How can you highlight the value in character pointers?

+3


source to share


3 answers


The type "hello"

is an array char

that decays into a pointer char

. Therefore, you can use it to initialize a type variable char*

.

Type 10

- int

. It cannot be implicitly converted to int*

and is therefore int *a = 10

invalid. Perhaps the closest int

equivalent to your example char

:



int arr[] = {1, 2, 3};
int *a = arr;

      

(There is also a constant issue here that I am not referring to to keep things simple. See this question if you want to know more.)

+8


source


This is because it "hello"

is a string literal that represents array

of char

. The starting address is array

assigned to the pointer b

in the assignment char *b = "hello"

.

10

is a type value int

and cannot be assigned to a pointer int

.



+6


source


Type a string literal in C ++ - it char const[6]

and char[6]

in C (the number of characters in the literal, including the terminating NUL).

While char *b = "hello";

legal in C, it is deprecated in C ++ 03 and illegal in C ++ 11. You should writechar const *b = "hello";

The reason it works is because both languages ​​define an implicit conversion of array types to a pointer to the first element of the array. This is commonly referred to as array decay.

This conversion is not applicable to int *a = 10;

, so it doesn't work in both languages.

+3


source







All Articles