c - 修复使用指针确定字符串长度的程序

标签 c string pointers

请解决这个问题......

#include<stdio.h>

main()
{
    char *name;
    int length;
    char *cptr=name;
    name="Delhi";
    printf("%s\n",name);
    while(*cptr != '\0')
    {
        printf("%c is stored at address %u\n",*cptr,cptr);
        cptr++;
    }
    length=cptr-name;
    printf("\n Length of the string = %d\n",length);
    return 0;
}
<小时/>

Screenshot

最佳答案

  • main()

    原型(prototype)不符合标准;它需要返回类型 int 。因此将其更改为:

    int main(void) 
    

    int main(int argc, char* argv[])
    
  • printf("%c is stored at address %u\n",*cptr,cptr);

    %u不是指针的正确说明符;您需要使用%p相反:

    printf("%c is stored at address %p\n",*cptr,(void*)cptr);
    
  • length=cptr-name;

    length类型为int也许你的机器是 64 位的,所以变量不能保存地址的差异,这会导致问题,所以最好使用 size_t .

    size_t length;
    

    并为最后一个输出更改适当的说明符:

    printf("\n Length of the string = %zd\n",length);
    
  • 关于仅使用指针获取字符串的长度,请输入 char *cptr=name;之后name="Delhi";

<小时/>

你的程序应该是:

#include <stdio.h>

main()
{
    char *name;
    size_t length;
    name="Delhi";
    char *cptr=name;
    printf("%s\n",name);
    while(*cptr != '\0')
    {
        printf("%c is stored at address %p\n",*cptr,(void *)cptr);
        cptr++;
    }
    length=cptr-name;
    printf("\n Length of the string = %zd\n",length);
    return 0;
}

关于c - 修复使用指针确定字符串长度的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42217923/

相关文章:

c - put 显示,但 %s 不显示

c - Makefile 条件包含

C 内联函数和内存使用

python - 使用 python (3.3.1) 在 html 源代码中搜索字符串

c++ - 这样做的正确方法是什么?调用指向指向指针的指针内部的函数?

c - 如何引用另一个 C 文件中的变量?

string - 如何将配置文件(行)转换为 Ansible 中的字典列表

java - 如何使用 Java 标准 API 从字符串中获取特定数据?

c - 指针数组的问题

没有 new 关键字和使用指针的 C++ 对象初始化