3

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?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Robin Mandela
  • 117
  • 1
  • 3
  • 11

3 Answers3

8

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.)

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

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.

rakeshbs
  • 24,392
  • 7
  • 73
  • 63
3

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.

Praetorian
  • 106,671
  • 19
  • 240
  • 328