char* and char arr[] Difference - C++/C -


just starting out in c++, wondering if explain something.

i believe can initialise char array in following way

 char arr[] = "hello" 

this create char array values 'h', 'e', 'l', 'l', 'o', '\0'.

but if create this:

 char* cp = "hello"; 

will create array, , pointer array?

eg: cp point first element ('h') in memory, additional elements of array?

the string literal has array type. in first example gave, there 2 arrays involved. first array containing string literal , second array arr you're declaring. characters string literal copied arr. c++11 wording is:

a char array (whether plain char, signed char, or unsigned char), char16_t array, char32_t array, or wchar_t array can initialized narrow character literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or appropriately-typed string literal enclosed in braces. successive characters of value of string literal initialize elements of array.

in second example, letting string literal array undergo array-to-pointer conversion pointer first element. pointer pointing @ first element of string literal array.

however, note second example uses feature deprecated in c++03 , removed in c++11 allowing cast string literal char*. valid c++11, have instead be:

const char* cp = "hello"; 

if use conversion char* in c++03 or in c, must make sure don't attempt modify characters, otherwise you'll have undefined behaviour.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -