c - 我的结果是 1 但我输入的字符串长度更长

标签 c

#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/

相关文章:

c - 我的 for 循环不起作用?

c - 在二维数组/矩阵中查找由 1 组成的正方形

c - 时间复杂度划分

比较两个文本文件 - C 语言拼写检查程序

c - 为什么我应该在这里使用 scanf_s 而不是 scanf ?

计数排序程序在 c 中的特定编译器中显示错误

arrays - 对数组中大于 n 的元素按升序排序并在 C 中降序排列

c - 我试图在一个函数中初始化一个 SDL_Window,但它总是失败,除非我定义 SDL_Window*win;作为全局变量

创建一个函数来复制 n 个字符,如 C 中的 strcpy

复制带有指向复制文件的符号链接(symbolic link)的目录(在目录树中)