Initializing a pointer variable

While C++ allows the use of char *b = {"Hello World!"}; why is it that doing the same with int does not work? i.e int *a = {10,20,30}; does not compile?

Also, is it valid to free the memory allocated to b using delete even though it was the value the pointer was initialized with?

Is it that creators of C++ have simplifier the syntax on purpose so the character array does not need to be written as char *b = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
Last edited on
why is it that doing the same with int does not work?
Because it is not the same thing.

"Hello World!" provides a pointer to a string. char *b requires a pointer to a string.

{10,20,30} provides an array of ints. int *a requires a pointer to an int. Change to int a[] = {10,20,30}.
But string is basically a character array right? That is why I have this question.
But you're not dealing with an array of char you're dealing with a pointer to a const string in your snippet.

Also look at the warning my compiler generates about that code:

main.cpp|7|warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]|

Is it that creators of C++ have simplifier the syntax on purpose so the character array does not need to be written as char *b = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'};

But remember this example is not the same as "Hello World", it is just an array of char where "Hello World" is a const string. A C-string is an array of char terminated by the end of string termination character ('\0').

Topic archived. No new replies allowed.