Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between char* and int* data type to create array of pointers in C++?

While creating an array of pointers for int data type the following code works:

int var[] = {10, 100, 200, 1000};
int *ptr[] = {&var[0], &var[1], &var[2], &var[3]};

While creating an array of pointers for char data type the following is legal:

char *names[] = {"Mathew Emerson", "Bob Jackson"};

But if I create an array of pointers for int data type as follows:

int var[] = {10, 100, 200, 1000};
int *ptr[] = {var[0], var[1], var[2], var[3]};

I get a compiler error. I understand why I am getting a compilation error in the above method of declaration for array of int data type, as var[i] is not a reference to a variable to which a pointer must point to i.e. its address, but shouldn't I also get error by the same logic in the declaration of my char array of pointer.

What is the reason that its is acceptable in char array of pointers?

Is " a string value " an address of something to which a pointer can point to or is it just a const string value.

like image 447
Natsu Avatar asked Jul 06 '16 11:07

Natsu


2 Answers

char *names[] = {"Mathew Emerson", "Bob Jackson"};

Is not legal in C++. A string literal has the type of const char[] so it is illegal to store it as a char* as it violates const-correctness. Some compilers allow this to still compile as a legacy from C since string literals have the type char[] but it is not standard C++. If you turn up the warnings on your compiler you should get something along the lines of

main.cpp: In function 'int main()':
main.cpp:5:53: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
     char *names[] = {"Mathew Emerson", "Bob Jackson"};

If you want an array of strings then I suggest you use a std::string like

std::string names[] = {"Mathew Emerson", "Bob Jackson"};

The reason

char *names[] = {"Mathew Emerson", "Bob Jackson"};

"works" is that since the string literals are arrays they implicitly decay to pointers so

{"Mathew Emerson", "Bob Jackson"}

Becomes

{ address_of_first_string_literal, address_of_second_string_literal}

and then those are used to initialize the pointers in the array.

int *ptr[] = {var[0], var[1], var[2], var[3]};

Cannot work because var[N] is a reference to the int in the array and not a pointer.

like image 89
NathanOliver Avatar answered Sep 19 '22 16:09

NathanOliver


"Mathew Emerson" is of type const char* - it is already a pointer, thus you can directly store it in an array of pointers. The reason you need & for the int case is to "convert" int to int*.

like image 35
majk Avatar answered Sep 21 '22 16:09

majk