TIN_MAN_025
TIN_MAN_025

Reputation: 15

User defined function with the same syntax as strlen() using only one variable other than the formal parameter?

All, i need to create a user defined function equivalent to strlen() in C code. However, this function named MyStrlen can only have two variables, the parameter variable and another that is of type "Const pointer to const char" i.e. const char * const START = s1. Here, s1 is the string the user inputs, I then call strlen and MyStrlen right after and compare the two as an output. My problem is im getting a warning: Value computed is not used in MyStrlen function and im getting a bunch of data loss warnings 'initializing': conversion from '__int64' to 'int', possible loss of data. Ive tried a lot of changes to no avail, and I am a novice programmer. Just started a few weeks ago in C/C++. Any help or direction would be greatly appreciated.

//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;
}

This is the main function:

#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;
}

Upvotes: 1

Views: 236

Answers (1)

0___________
0___________

Reputation: 67835

Very simple:

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

or as in your question:

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

Upvotes: 1

Related Questions