4. Characters and Pointers #
Created Monday 23 December 2019
Character arrays and pointers have a different behavior, as compared to numerical data types.
- cout behaves differently for character pointers and array names(i.e addresses), instead of printing the address, it prints the value at the address till we reach a memory byte where we have a null character.
- cin, if taken in a memory address or array name, will make a temporary memory for storing all input, when it encounters a whitespace, it copies all the elements from the** temporary space to a contiguos memory space** of the (to be string’s) length.
Note: This is okay. But initializing a char* with a string may or may not work. As the literal is stored in the temporary memory which may or may not be readable after taking the input. So, the safe method is to not initialize the pointer directly using *string literal. *Note that such a declarization is available only for strings and not for any other data type. e.g int x = 2 is invalid, while char x =“sanjar” will generate warnings but unsafe.
- assignment exception: char* x = “sanjar” is valid. Although, this is invalid in -pedantic flag. = has been overloaded for character addresses(pointers and array names).
Note:
- These 3 cases and only these 3 cases are an anomaly, no other exceptions are there for character arrays. So, *derefencing *char *, works the same as it does for integers and other data types.
- Referencing(using &), cannot help us know the length of the string(or any array in general). As it operates on the address and not on the sizeof() value in the symbol table.