Reputation: 115
When I type int * a = 10
it shows error .But when I give char *b = "hello"
it doesn't shows error ?
We can't initialize values directly to pointers but how it is possible only in char
. How it is possible to allocate value in the character pointers?
Upvotes: 3
Views: 126
Reputation: 24572
This is because "hello"
is a string literal that represents an array
of char
. The starting address of the array
is assigned to the pointer b
in the assignment char *b = "hello"
.
10
is a value of type int
and cannot be assigned to a pointer of int
.
Upvotes: 6
Reputation: 500367
The type of "hello"
is a char
array, which decays into a char
pointer. You can therefore use it to initialize a variable of type char*
.
The type of 10
is int
. It cannot be implicitly converted to int*
and hence int *a = 10
is not valid. The following is perhaps the closest int
equivalent to your char
example:
int arr[] = {1, 2, 3};
int *a = arr;
(There is also an issue with constness here, which I am not addressing to keep things simple. See this question if you'd like to learn more.)
Upvotes: 8
Reputation: 109149
The type of the string literal in C++ is char const[6]
, and char[6]
in C (it's the number of characters in the literal, including the terminating NUL character).
While char *b = "hello";
is legal in C, it is deprecated in C++03, and illegal in C++11. You must write char const *b = "hello";
The reason that 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 decay of the array.
No such conversion is applicable to int *a = 10;
, so that fails in both languages.
Upvotes: 3