N
N
nkorobkov2016-02-13 14:01:57
C++ / C#
nkorobkov, 2016-02-13 14:01:57

Why does a char take 1 byte, but a string with one character takes 2 bytes?

Heard something about adding " \0 " to the end of lines, but did not go into details. Who knows, please answer!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kirill Romanov, 2016-02-13
@nkorobkov

That's right, this 1 byte occupies the end-of-line character '\0'

A
asd111, 2016-02-13
@asd111

one letter can be of type char or w_char
char- one ASCII character occupies one byte
w_char- one UTF-16 encoded letter occupies 2 bytes
\0- end-of-line character, used for printf etc. the functions knew where the memory area allocated for the string ends.
const char *name = "name";- the end-of-line character will be set by the compiler itself and the length of the string will be not 4 bytes, but 5, but at the same time strlen should return the length up to \0 i.e. 4 bytes, although actually 5 bytes are stored
Something like this. In other words, if you need a string, then you need to do 1 more byte.
In this regard, it's easier to use C++ std::string, std::wstringorQstring

T
Tsiren Naimanov, 2016-02-13
@ImmortalCAT

char is 1 character
string is a string + its length

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question