strcpy 和 strnpy 区别
与strncpy的区别
第一种情况:
1 2 3 4 | char * p= "how are you ?" ; char name[20]= "ABCDEFGHIJKLMNOPQRS" ; strcpy (name,p); //name改变为"how are you ? "====>正确! strncpy (name,p, sizeof (name)); //name改变为"how are you ?" =====>正确!后续的字符将置为NULL |
第二种情况:
1 2 3 4 5 6 | char * p= "how are you ?" ; char name[10]; strcpy (name,p); //目标串长度小于源串,错误! name[ sizeof (name)-1]= '\0' ; //和上一步组合,弥补结果,但是这种做法并不可取,因为上一步出错处理方式并不确定 strncpy (name,p, sizeof (name)); //源串长度大于指定拷贝的长度sizeof(name),注意在这种情况下不会自动在目标串后面加'\0' name[ sizeof (name)-1]= '\0' ; //和上一步组合,弥补结果 |