char str[] = "313233414243"; //系统会在str后面加一个字符串结束符 ‘\0’
std::cout<<"strlen(str): "<<strlen(str)<<std::endl; //12个字节 使用strlen不计算字符串结束符 ‘\0’
std::cout<<"sizeof(str): "<<sizeof(str)<<std::endl; //13个字节 使用sizeof计算字符串结束符 ‘\0’
===================================
int main(int argc, char * argv[])
{
int nRet = 0;
char *ptr = "\0";
printf("sizeof1:%d\n", sizeof(ptr)); <------ 指针大小, 4字节
printf("strlen2:%d\n", strlen(ptr)); <----- strlen 计算字符串长度,到\0结束
printf("sizeof3:%d\n", sizeof("\0")); <---- sizeof 计算包括结束符 "\0" 实际在内存是 \0\0 (最后一个编译器加入的字符串结束符), 所以结果是2
printf("strlen4:%d\n", strlen("\0"));
printf("sizeof5:%d\n", sizeof(" "));
printf("strlen6:%d\n", strlen(" "));
printf("sizeof7:%d\n", sizeof(""));
printf("strlen8:%d\n", strlen(""));
}
输出:
sizeof1:4
strlen2:0
sizeof3:2
strlen4:0
sizeof5:2
strlen6:1
sizeof7:1
strlen8:0