把指针改为数组以后为什么一直报错呢
#include
int StringLen( char a[] ); /*const here just count the length of the string
and use avoid modifying the original string.*/
{
int count = 0; /*declaration*/
while (a!='\0') /*The strlen function ends with '\0'
and does not calculate a length containing '\0'.*/
{
++count;
++a;
}
return count;
/* for (count = 0; *p != '\0'; p++)
count++;
This for loop is in the same function of the while loop */
}
int main()
{
char a[]=“Hello world”;
Printf(“len is %d\n”, StringLen( a );
return 0;
}
函数 StringLen 中使用了数组作为参数,但是在函数内部使用了指针的方式来遍历数组。编译器会报错。
① 可以在函数内部使用数组的方式来遍历字符串,例如:
int StringLen(char a[]) {
int count = 0;
for (int i = 0; a[i] != '\0'; i++) {
count++;
}
return count;
}
② 也可以在函数内部使用指针的方式来遍历字符串,但是需要把参数改为指针,例如:
int StringLen(char *a) {
int count = 0;
while (*a != '\0') {
count++;
a++;
}
return count;
}
函数后面的分号去掉
函数体修改下:
int StringLen( char a[] )
{
int count = 0;
while (a[count]!='\0')
{
++count;
}
return count;
}