标签:bool div code amp 字符串常量 col ptr 策略 函数
1.链接代码
char* my_strcat(char* dist, const char* src) { if (dist == nullptr || src == nullptr) { return dist; } char* cp = dist; while (*cp != ‘\0‘) { ++cp; } while (*cp = *src) { cp++; src++; } return dist; }
int main() { char stra[30] = {"yhping"}; char strb[30] = {"hello"}; char strc[30] = {};
my_strcat(stra, strb);
printf("stra = %s \n", stra); // stra => "yhpinghello"; // strb =>"hello"; }
dist等于y,++到\0;
若stra为空字符串,则变为拷贝函数,此函数第一步dist遇见\0,++遇见\0,c中以\0结尾
2.比较
1.int my_strcmp(const char* first, const char* second) { assert(first != nullptr && second != nullptr); int k = 0; while ((k = *first - *second) == 0 && *first++ && *second++);//比较的优先级高于逻辑的优先级 return k; }
//yhping yhpa yhping
//yhping 相同,直到\0退出 yhping a小于i,小于0,退出 yhpa i大于a,大于0,退出 2.int my_strcmp(const char* first, const char* second) { assert(first != nullptr && second != nullptr); while (*first != ‘\0‘ && *second != ‘\0‘) { if (*first != *second) { break; } } return *first - *second; }
int main() { char stra[30] = {"yhping"}; char strb[30] = {"yhp"}; char strc[30] = {};
3.
int main() { char stra[] = { "yhping" }; char strb[] = { "yhping" }; char* strc = "yhping";//加const称为静态常量 char* strd = "yhping";//为字符串常量 bool x = (stra == strb); bool y = (strc == strd); // x // y; stra[0] = ‘x‘; // ok//stra已近给x开辟空间,可以改变y为x //strc[0] = ‘x‘; // error;//strc指向的是字符串常量只允许读值不允许改值 return 0; }
数组名代表数组首元素的地址,stra ,strb首地址不同,因此x错误
字符串常量在data 区,strc,strd是指针,开辟四字节,存放字符串首地址
4.
标签:bool div code amp 字符串常量 col ptr 策略 函数
原文地址:https://www.cnblogs.com/xpei-1124/p/14610064.html