下面的程序先输入一个字符串,定义一个字符型指针变量p,p指向该字符串。然后循环判断每一个字符,如果不是空字符'\0',那么就将变量num自加一,num就是该字符串的长度。最后输出num,即字符串的长度。
#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[100];
char * p;
int num;
num=0;
printf("please input a string:\n");
scanf("%s",str);
p=str;
for(p;*p!='\0';p++)
{
num++;
}
printf("the length is %d\n",num);
return 0;
}
运行结果如下,也可以自己跑一下程序,就看到结果了
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/7a899e510fb30f24ac352ddecd95d143ac4b0344?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)