1

所有,我需要创建一个等效strlen()于 C 代码的用户定义函数。但是,这个命名的函数MyStrlen只能有两个变量,参数变量和另一个类型为“Const pointer to const char”的变量,即const char * const START = s1。这里s1是用户输入的字符串,然后我调用 strlen 和 MyStrlen 并将两者作为输出进行比较。我的问题是我得到了一个warning: Value computed is not used函数MyStrlen并且我得到了一堆数据丢失警告'initializing': conversion from '__int64' to 'int', possible loss of data。我尝试了很多更改均无济于事,而且我是新手程序员。几周前刚开始使用 C/C++。任何帮助或方向将不胜感激。

//Equivalent to strlen:

#include <stddef.h>

size_t MyStrlen(const char *s1)
{
    const char * const START = s1;

    //Iterate through the string until the null operator is encountered
    while (*s1 != '\0')
    {
        *(s1++);

    }
    //Find the difference between the two strings and return that value
    int Difference = s1 - START;

    return (int)Difference;
}

这是主要功能:

#include <stdio.h>
#include <string.h>

size_t MyStrlen(const char *s1);

const int STR_SIZE = 100;
const int LENGTH = (STR_SIZE + 1); //To account for the null zero at the end

int main(void)
{
    char s1[LENGTH];

    printf("Please enter any space separated string: ");

    //Pull in string and replace the newline character with the null zero
    fgets(s1,STR_SIZE,stdin);
    s1[strcspn(s1, "\n")] = '\0';

    //Call both the library function strlen, and the function we created
    int Macro_value = strlen(s1);
    int My_value = MyStrlen(s1);

    //Output the string and the difference in string length between the
    //two functions
    printf("\nstrlen(\"%s\") returned %d\n"
           "MyStrlen(\"%s\") returned %d\n", s1, Macro_value,
           s1, My_value);

    return 0;
}
4

1 回答 1

1

非常简单:

size_t mystrlen(const char *str)
{
    const char *end = str;
    if(str)
    {
        while(*end) end++;
    }
    return (uintptr_t)end-(uintptr_t)str;
}

int main(void)
{
    printf("%zu\n", mystrlen(NULL));
    printf("%zu\n", mystrlen(""));
    printf("%zu\n", mystrlen("123"));
}

https://godbolt.org/z/bMTvnc

或在您的问题中:

size_t mystrlen(const char *str)
{
    const char * const start = str;
    if(str)
    {
        while(*str) str++;
    }
    return (uintptr_t)str-(uintptr_t)start;
}
于 2020-11-08T14:22:33.467 回答