[Solved] Difference between char , char[] , char * [closed]


char represents a character (allocated on the stack). If you want to set it to empty, use char c="\0" or char c = (char) 0.

char* cPtr is a pointer to a character. You can allocate an empty character on the heap with char* c = new char('\0').

char c[n] is a character array of size n.


Edit

As people have correctly pointed out below, a char is never empty, in the same sense as a container such as std::vector or std::string can be empty. A char is not fundamentally different to, say, an int, it’s just shorter (1 byte as opposed to 2 or 4 or 8). Can an int be empty? Not as such; it can be zero, meaning that all its bits are set to zero in memory, and the same goes for a char. char c="\0" will be represented as “00000000” on the stack.

A pointer to a char (char* cPtr), on the other hand can be ’empty’ in the sense that it can point nowhere, by setting it to NULL. In this case, the pointer itself will exist on the stack and will contain a special sequence of 0/1’s that your system interprets as NULL. Once you do cPtr = new char('\0'), a char (i.e. a byte) will be allocated on the heap and set to “00000000”, and the value of cPtr on the stack will be changed to point to the address of the new character on the heap.

PS: don’t actually do char* cPtr = new char('\0'), use an std::vector<char> or an std::string. Also, you may want to look into smart pointers.

3

solved Difference between char , char[] , char * [closed]