new char数组一点小疑点
new char数组一点小问题
char* temp = new char[4];
//memset(temp,0,sub_len+1);
strncpy(temp,src_p,sub_len); //调试到这步时候为什么显示无效字符串
temp[sub_len] ='\0'; //加上结束符才显示字符串为什么
一定要将爱上结束字符吗?必须要memset吗?
------解决方案--------------------
strncpy(temp,src_p,sub_len);
如果最后的sub_len长度比src_p大,那temp字符串就没有问题
memset清零只是一个习惯,可以有效防止各种意外
不过因为这个函数的低效率,我们这边程序都不会这么写,由自己保证temp字符串确实以'\0'结尾
temp[sub_len] ='\0';,回答通第一个问题,如果sub_len比src_p长度大,这个可以不要
------解决方案--------------------
第二个问题,memset不是必须的,一般为了避免问题,建议使用,但不能过度使用。它更适用于较大的结构体或数组清零,快速便捷,但是需要慎用,因为会对指定的所有字节置零,有可能导致指针指向内存错误
------解决方案--------------------
The strncpy() function copies not more than n bytes (bytes that follow a null byte are not copied) from the array pointed to by s2 to the array pointed to by s1. If copying takes place between objects that overlap, the behaviour is undefined.
If the array pointed to by s2 is a string that is shorter than n bytes, null bytes are appended to the copy in the array pointed to by s1, until n bytes in all are written.
strncpy的解释
还有最关键的一句:
If there is no null byte in the first n bytes of the array pointed to by s2, the result will not be null-terminated.
char* temp = new char[4];
//memset(temp,0,sub_len+1);
strncpy(temp,src_p,sub_len); //调试到这步时候为什么显示无效字符串
temp[sub_len] ='\0'; //加上结束符才显示字符串为什么
一定要将爱上结束字符吗?必须要memset吗?
------解决方案--------------------
strncpy(temp,src_p,sub_len);
如果最后的sub_len长度比src_p大,那temp字符串就没有问题
memset清零只是一个习惯,可以有效防止各种意外
不过因为这个函数的低效率,我们这边程序都不会这么写,由自己保证temp字符串确实以'\0'结尾
temp[sub_len] ='\0';,回答通第一个问题,如果sub_len比src_p长度大,这个可以不要
------解决方案--------------------
第二个问题,memset不是必须的,一般为了避免问题,建议使用,但不能过度使用。它更适用于较大的结构体或数组清零,快速便捷,但是需要慎用,因为会对指定的所有字节置零,有可能导致指针指向内存错误
------解决方案--------------------
The strncpy() function copies not more than n bytes (bytes that follow a null byte are not copied) from the array pointed to by s2 to the array pointed to by s1. If copying takes place between objects that overlap, the behaviour is undefined.
If the array pointed to by s2 is a string that is shorter than n bytes, null bytes are appended to the copy in the array pointed to by s1, until n bytes in all are written.
strncpy的解释
还有最关键的一句:
If there is no null byte in the first n bytes of the array pointed to by s2, the result will not be null-terminated.