C style strings, Pointers, arrays

前端 未结 3 672
自闭症患者
自闭症患者 2021-02-01 09:46

I\'m having trouble understanding what a C-style string is. Happy early New Year

What I know: A pointer holds a memory address. Dereferencing the pointer will give you

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 10:00

    Printing out a char* with cout works differently from printing, say, an int* with cout. For compatibility with C-style strings, the overloaded version of << which takes a char* argument treats the char* as a C-style string. If you want to print the memory address that a char* holds, you can cast it to a void*.

    Yes, if you write either of

    char *s1 = "hi lol";
    char s2[] = "hi haha";
    

    a NUL (\0) terminator is added for you at the end of the string. The difference between these two is that s1 is a pointer to a string literal the contents of which you are not, according to the C standard, supposed to modify, whereas s2 is an array, that is, a block of memory allocated for you on the stack, which is initialized to hold the value "hi haha", and you are free to modify its contents as you please. The amount of memory allocated for the array is exactly enough to hold the string used as the initializer, and is determined for you automatically, which is why the square brackets can be empty.

    One side note: in C, if you enter char s[3] = "abc";, then s will be initialized to {'a', 'b', 'c'}, without a NUL terminator! This is because of a clause in the standard that says that strings in this context are initialized with a NUL terminator if there is room in the array (or some similar wording). In C++ this is not the case. For more, see No compiler error when fixed size char array is initialized without enough room for null terminator.

    Edit, in response to your added question: If you have char *s = "...", and you cout << &s;, it will print the address where the pointer s is stored, rather than the address that s holds (the address of the first element of the string to which s refers).

提交回复
热议问题