Find the size of a string pointed by a pointer

前端 未结 9 924
一整个雨季
一整个雨季 2020-12-08 20:39
#include 

int main ()
{
    char *ptr = \"stackoverflow\"

}

Is there any way to find the length of stackoverflow pointed by ptr, a

相关标签:
9条回答
  • 2020-12-08 21:05

    Purely using pointers you can use pointer arithmetic:

    int strLen(char *s)
    {
        int *p = s;
        while(*p !=’\0’)
        {
            p++;  /* increase the address until the end */
        }
        Return p – s; /* Subtract the two addresses, end - start */
    }
    
    0 讨论(0)
  • 2020-12-08 21:09
    #include<stdio.h>
    main()
    {
        int mystrlen(char *);
        char str[100];
        char *p;
        p=str;
        printf("Enter the string..?\n");
        scanf("%s",p);
        int x=mystrlen(p);
        printf("Length of string is=%d\n",x);
    
    
    }
    int mystrlen(char *p)
    {
        int c=0;
        while(*p!='\0')
        {
            c++;
            *p++;
        }
        return(c);
    }
    

    simple code to understand

    0 讨论(0)
  • 2020-12-08 21:10

    Use strlen to find the length of (number of characters in) a string

    const char *ptr = "stackoverflow";
    size_t length = strlen(ptr);
    

    Another minor point, note that ptr is a string literal (a pointer to const memory which cannot be modified). Its better practice to declare it as const to show this.

    0 讨论(0)
提交回复
热议问题