下面是一段 C 语言的 代码片段。
介绍如何使用 strncpy, memcpy 操作字符,字符串。
void printData(char* data, int len, char* comment){ if(comment){ printf("========== printData:%s==========\n", comment); } for(int i=0;i<len; ++i){ if((i+1)%16 == 0){ printf("0x%02x \n", data[i]); }else{ printf("0x%02x ", data[i]); } } printf("\n\n"); } void test3(){ char szData30_1[30] = {0}; char szData30_2[30] = {0}; char szData16_1[16] = {0}; char szData16_2[16] = {0}; char szData16_3[16] = {0}; char szData16_4[16] = {0}; // 字符 "1" 的 ASCII 是 49 (0x31) strncpy(szData30_1, "1234567812345678", sizeof(szData30_1)-1); strncpy(szData30_2, "C*CORE SYS @ SZ ", sizeof(szData30_2)-1); memcpy(szData16_1, szData30_1, 16); memcpy(szData16_2, szData30_2, 16); memcpy(szData16_3, "1234567812345678", 16); memcpy(szData16_4, "C*CORE SYS @ SZ ", 16); printData(szData30_1, sizeof(szData30_1), "szData30_1"); // 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 // 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 printData(szData30_2, sizeof(szData30_2), "szData30_2"); // 0x43 0x2a 0x43 0x4f 0x52 0x45 0x20 0x53 0x59 0x53 0x20 0x40 0x20 0x53 0x5a 0x20 // 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 printData(szData16_1, sizeof(szData16_1), "szData16_1"); // 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 printData(szData16_2, sizeof(szData16_2), "szData16_2"); // 0x43 0x2a 0x43 0x4f 0x52 0x45 0x20 0x53 0x59 0x53 0x20 0x40 0x20 0x53 0x5a 0x20 printData(szData16_3, sizeof(szData16_3), "szData16_3"); //这个同上 printData(szData16_4, sizeof(szData16_4), "szData16_4"); }
标签:comment,字符,int,char,拷贝,memcpy,strncpy From: https://www.cnblogs.com/music-liang/p/18364489