简体   繁体   中英

size_t return pointer subtraction

I want to rthe following error message......error: invalid conversion from 'const char*' to 'size_t'

    return 0;
}

size_t strlen(const char *s1)
{



    return s1 - 0;
}

Subtracting zero from a pointer does not change the pointer, the same way that subtracting zero from a number does not change a number.

You should subtract the original pointer, not zero, to get the length:

size_t strlen(const char *s1) {
    const char *orig = s1;
    while (*s1) {
        s1++;
    }
    return s1 - orig;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM