#include <stdio.h>
int length(char *point)
{
int n=0;
if (*point!='\0')
{
point++;
n++;
}
return n;
}
void main()
{
int m;
char *point;
char chars[80];
printf ("please enter a chars\n");
gets(chars);
point=chars;
m=length(chars);
printf("The length of the chars is %d.\n",m);
}
请问为什么不能加“n”? 我认为问题是关于点的使用,但我找不到它。 谢谢。
最佳答案
size_t length(const char *point)
{
size_t n = 0;
while (*point != '\0') // Need to loop to iterate through point
{
point++;
n++;
}
return n;
}
我会像那样在 main
中使用它:
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
// The 79 is there to limit the input to the size you allocated in chars[80]
// Thus avoiding buffer overflow
size_t m = length(chars);
printf("The length of the chars is %zu.\n",m);
return 0;
}
您忘记遍历字符串。您增加了指针,仅此而已。另外,我建议使用 strlen()
来完成您想要做的事情。
使用 strlen()
:
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
size_t m = strlen(chars);
printf("The length of the chars is %zu.\n", m);
return 0;
}
关于c - 我的结果是 1 但我输入的字符串长度更长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44456399/