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


while creating array of pointers int data type following code works:

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

while creating array of pointers char data type following legal:

char *names[] = {"mathew emerson", "bob jackson"}; 

but if create array of pointers int data type follows:

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

i compiler error. understand why getting compilation error in above method of declaration array of int data type, var[i] not reference variable pointer must point i.e. address, shouldn't error same logic in declaration of char array of pointer.

what reason acceptable in char array of pointers?

is " a string value " address of pointer can point or const string value.

char *names[] = {"mathew emerson", "bob jackson"}; 

is not legal in c++. string literal has type of const char[] illegal store char* violates const-correctness. compilers allow still compile legacy c since string literals have type char[] not standard c++. if turn warnings on compiler should along lines of

main.cpp: in function 'int main()': main.cpp:5:53: warning: iso c++ forbids converting string constant 'char*' [-wpedantic]      char *names[] = {"mathew emerson", "bob jackson"}; 

if want array of strings suggest use std::string like

std::string names[] = {"mathew emerson", "bob jackson"}; 

the reason

char *names[] = {"mathew emerson", "bob jackson"}; 

"works" since string literals arrays implicitly decay pointers so

{"mathew emerson", "bob jackson"} 

becomes

{ address_of_first_string_literal, address_of_second_string_literal} 

and used initialize pointers in array.

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

cannot work because var[n] reference int in array , not pointer.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -