Pointers and Strings C++

前端 未结 9 1160
栀梦
栀梦 2020-12-24 15:31

I\'m teaching myself C++ and I\'m a bit confused about pointers (specifically in the following source code). But first, I proceed with showing you what I know (and then cont

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 15:50

    Pointers are not the same as arrays. String literals are immutable, and when you have a pointer to a string literal, you can inspect its contents, but modifying them are undefined behavior. When using this syntax:

    char arr[] = "hi there";
    

    The string literal is copied into the array. Because you do not specify a size, the compiler automatically deduces it. The NUL terminator is automatically added as well. If you specify a size, you must make sure that the buffer can hold the NUL terminator. Therefore:

    char arr[5] = "hello";
    

    is a mistake. If you use the brace initializer syntax:

    char arr[5] = { "h", "e", "l", "l", "o" };
    

    This is a mistake because there is no NUL terminator. If you use strcpy, a NUL terminator will be added for you.

    std::string provides two methods of returning a pointer to its underlying contents: data and c_str. Pre-C++11, the only difference is data does not include the NUL terminator. In C++11, it now does, so their behavior is identical. Because the pointer can easily be invalidated, is not safe to manipulate those pointers. It is also not safe to do char * ptr = str.c_str(); because the lifetime of the array returned by c_str dies at the semi-colon. You need to copy it into a buffer.

提交回复
热议问题