字符指针==的意义:判断两个指针是否指向同一地址
字符指针存在栈里,字符串存在字符数组里(静态数组在栈里)或者在字符常量区,字符常量区没有重复的字符串
int main() { char *s1 = "abc";//s1在栈上,"abc"在字符常量区,s3也指向这个"abc" char *s3 = "abc"; char s2[] = "abc";//"abc"在栈上 char *s4 = new char[10]; char *s5 = static_cast<char*>(malloc(10)); cout << &(s2[0]) << endl;//以下四条语句都是输出abc cout << &s1[0] << endl; cout << &s3[0] << endl; cout << s1 << endl; cout << strcmp(s1, s2) << endl; cout << (s1 == s2) << endl;//判断是否指向同一地址 cout << (s1 == "abc") << endl; cout << (s2 == "abc") << endl; printf("%p,%p,%p", s1, s2, s3); }
memcpy拷贝字符串,第三个参数需要自己控制,strcpy不需要,只需要两个指针就行;下面的代码问题在哪儿?
1 void AddStr(char *pBuffer, char*pStrSrc1, char*pStrSrc2) 2 { 3 memcpy(pBuffer, pStrSrc1, strlen(pStrSrc1)); 4 memcpy(pBuffer + strlen(pStrSrc1), pStrSrc2, strlen(pStrSrc2));//没有复制pStrSrc2结尾的空字符到pBuffer 5 //memcpy(pBuffer + strlen(pStrSrc1), pStrSrc2, strlen(pStrSrc2)+1); 6 *(pBuffer + strlen(pStrSrc1) + strlen(pStrSrc2)) = ‘\0‘; 7 } 8 void TestFunc() 9 { 10 char ayBuffer[256]; 11 char* pStrSrc1 = "our site is "; 12 char* pStrSrc2 = "10jqka.com.cn"; 13 AddStr(ayBuffer, pStrSrc1, pStrSrc2); 14 printf(ayBuffer); 15 16 }
AddStr用strcpy来实现,strcpy会自动在结尾加上空字符,strcpy比mencpy多了一个空字符处理时间,只调用了一次strlen,两者都遍历了两个字符串各一次
1 void AddStr(char *pBuffer, char*pStrSrc1, char*pStrSrc2) 2 { 3 4 strcpy(pBuffer, pStrSrc1); 5 strcpy(pBuffer + strlen(pStrSrc1), pStrSrc2);//从上次空字符处开始覆盖 6 }
时间: 2024-10-12 04:49:29