如何在不使用for循环的情况下获取char*变量的大小?

tis*_*rum 0 c pointers sizeof char

char *foo(char *dest, const char *src) {
    size_t i;                      
    for (i = 0; dest[i] != '\0'; i++);
Run Code Online (Sandbox Code Playgroud)

在这里,我正在迭代以获得dest的大小.在这种情况下,我将"hello"输入到dest中,其大小为6.当我尝试使用sizeof(dest)时,我得到4作为返回值.我希望能够在不使用for循环的情况下获取dest内部的内容大小.

char *foo(char *dest, const char *src) {
    while (*dest != '\0') dest++;           /* increment the length of dest's pointer*/
Run Code Online (Sandbox Code Playgroud)

编辑::我想花点时间表明我能够直接找到长度.

这是strcat程序的一部分.要求是不要使用[]括号来访问或在内存中移动.

char *strcat(char *dest, const char *src) {
    while (*dest != '\0') dest++;           /* increment the length of dest's pointer*/
    while (*src != '\0')                    /* we will be incrementing up through src*/
        *dest++ = *src++;                   /* while this is happening we are appending
                                             * letter by letter onto the variable dest
                                             */
    *(dest++) = ' ';                        /* increment up one in memory and add a space */
    *(dest++) = '\0';                       /* increment up one in memory and add a null
                                             * termination at the end of our variable dest
                                             */
    return dest;                            /* return the final output */
}
Run Code Online (Sandbox Code Playgroud)

小智 6

对于以null结尾的字符串,您必须迭代每个字符以计算长度.即使你使用strlen()它也会做你的循环.