这个例子与下面两个代码是一个道理.
2> 几个常用字符函数的编写。
1>>> strcat(s,t)函数,把t指向的字符复制到s指向的字符后面?——注意'\0'
#include <stdio.h>
#include <assert.h>
/* strcat(ps, t): Copy the charactor pointed
* by t append to the character pointed by s
*/
void *strcat(char *ps, char *t){
char *addr = ps;
assert((ps != NULL) && (t != NULL));
while(*ps){ /* The s point to the last character */
ps++;
}
while(*ps++ = *t++){ /* Copy t append to the s*/
}
return addr;
}
int main(){
char s[5] = "AB";
char *t = "E";
printf("%s\n", strcat(s, t));
return 0;
}
注意:在strcat里的两个指针ps和t,方法结束后,这两个函数都指向'\0'后面,因为ps++操作是"先取结果,后自增"
内存变化:
金玉岚

int strlen(char *p){
int iLen = 0;
while(*p){
iLen++;
p++;
}
return iLen;
}
/* strend:find t in s */
int strend(char *s, char *t){
int sLen = strlen(s);
int tLen = strlen(t);
if(tLen > sLen) return 0;
while(*s)
s++;
while(*t)
t++;
for(;tLen--;){
if(*--t != *--s) return 0;
}
return 1;
}
int main(){
char *s = "Hell Wold , Chuanshanjia";
char *t = "Chuanshanjia";
printf("%d\n", strend(s, t));
return 0;
}

1 #include <stdio.h>
2
3 int strlen(char *p){
4 int i = 0;
5 while(*p){
6 p++;
7 i++;
8 }
9
10 return i;
11 }
12
13 /* t中最多前n个字符复制到s中 */
14 char *strncpy(char *s, char *t, int n){
15 char *addr = s;
16 if(!strlen(s) || !n) return 0;
17
18 int tLen = strlen(t);
19 if(!tLen) return 0;
20
21 if(tLen < n)
22 n = tLen;
23
24 // Move the pointer s to the last
25 while(*++s) ;
26
27 while(n--){
28 *s++ = *t++;
29 }
30
31 return addr;
32
33 }
34
35
36
37 int main(){
38 char s[20] = "Hell World ";
39 char *t = "Chuanshanjia";
40
41 printf("%s\n", strncpy(s, t, 2222));
42 return 0;
43 }
解释:
>> argv是一个指向指针数组的指针。
所以接受参数也可以写成:
结合上图,我们可以这样理解:从里向外看
1.阅读——从右向左规则。
>> 规则符号:
-----------------------------------------------------------
* 读作"指向...的指针"
[] 读作"...的数组"
() 读作"返回...的函数"
-----------------------------------------------------------
下面两个示例:
int *f() ; // f: 返回指向int型的指针
>>步骤:
1)找标识符f:读作"f是..."
2)向右看,发现"()"读作"f是返回...的函数"
3)向右看没有什么,向左看,发现*,读作"f是返回指向...的指针的函数"
4)继续向左看,发现int,读作"f是返回指向int型的指针的函数"
int (*pf)(); // pf是一个指针——指向返回值为int型的函数
1)标识符pf,读作“pf是...”
2)向右看,发现),向左看,发现*,读作 "pf是指向...的指针"
3)向右看,发现"()",读作“pf是指向返回...的函数的指针"
4)向右看,没有,向左看发现int,读作"pf是指向返回int型的函数的指针"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架