如下代码:上下两段计算出来的sizeof(*p)均为1,但是后面注释(不是我写的)为什么一个是contains a null character,一个是didn't contain null character? //string 转化为char* string str="good boy"; const char *p=str.c_str(); //contains a null character cout << str<< endl; cout << *p << sizeof(*p)<< endl; /*string str="good boy"; const char *p=str.data(); //didn't contain null character cout << str<< endl; cout << *p << sizeof(*p)<< endl; */ return 0;
c_str()返回的指针指向null-terminated(字符串结束符'\0')的字符数组,即最后位置是一个null字符。
data()在C++11之前返回数组是不以'\0'结束的,在C++11之后功能和c_str()相同了。
原文参考链接:
https://en.cppreference.com/w/cpp/string/basic_string/c_str
Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.
The pointer is such that the range [c_str(); c_str() + size()]
is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.
https://en.cppreference.com/w/cpp/string/basic_string/data
The returned array is not required to be null-terminated.(until C++11)
The returned array is null-terminated, that is, data()
and c_str() perform the same function.(since C++11)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
typedef struct MessageData{
char Line_1[16];
char Line_2[16];
char Line_3[16];
char Line_4[16];
char Line_5[16];
char Line_6[16];
} MessageData;
MessageData message;
int main(){
MessageData * p = &message;
sprintf(p->Line_1, "%s", "1234");
sprintf(p->Line_2, "%s", "5678");
p->Line_1[15] = 0x20;
cout << strlen((char*)p) << " " << sizeof(p) << " " << sizeof(message) << " " << strlen(p->Line_1) << " " << strlen((char*)p->Line_1) << " " << " " << sizeof((char*)p->Line_1)<<" " << sizeof(p->Line_1);
}
观察如下代码 自己得出结论吧。
c++像漂亮的姑娘一样,会骗人。
C和C++完整教程:https://blog.csdn.net/it_xiangqiang/category_10581430.html
C和C++算法完整教程:https://blog.csdn.net/it_xiangqiang/category_10768339.html