#include <stdio.h>
#include <string.h>
int main(void)
{
unsigned char des[8]={"0123456"};//--->7
unsigned char src[4]={"999"};
//memcpy(des,src,3);//9993456--->最后的0没有拷贝
//memcpy(des,src,4);//999--->结束符也过去了
//memcpy(des,src,5);//结果同上 说明没事儿
memcpy(des,src,GMIN(8,strlen((char*)src)));//结果同上3 9993456
printf("%s\n",des );
}
为了安全可以:
#define GMIN(a,b) ((a)<(b))?(a):(b)
memcpy(des,src,GMIN(8,strlen(src)));
另外一个 也是我的原创歌曲!!
#include <stdio.h>
#include <string.h>
#define GMIN(a,b) ((a)<(b))?(a):(b)
int main(void)
{
#if 0
unsigned char des[8]={"0123456"};//--->7
unsigned char src[4]={"999"};
//memcpy(des,src,3);//9993456--->最后的0没有拷贝
//memcpy(des,src,4);//999--->结束符也过去了
//memcpy(des,src,5);//结果同上 说明没事儿
memcpy(des,src,GMIN(8,strlen((char*)src)));//结果同上 说明没事儿
printf("%s\n",des );
#else
char des[8]={"0123456"};//--->7
const char src[4]={"999"};
//sprintf(des,"%s",src);//结果 999
//printf("%s\n",des );
//sprintf(des,"%.2s",src);//结果 99
//printf("%s\n",des );
sprintf(des,"%.*s",4,src);//结果 999 也就是比src大也不要紧
printf("%s\n",des );
//结论:可以安全了!!
//sprintf(des,"%.*s",4,src);参数1des 参数2"%.*s"参数3是个数我们放置数组的大小。参数4哈哈再大也安全
#endif
}
int main(void)
{
char des[8]={"0123456"};//--->7
const char src[40]={"999999999999999999999999999999"};
sprintf(des,"%.*s",8,src);
printf("%s\n",des );
}