首页 > 解决方案 > 为什么这会打印字符串的错误部分?

问题描述

void buggy_substring(char *input, size_t pos, size_t len)
{
 input += pos;
 input[len] = '\0';
} 

int main(int argc, char *argv[])
{
 char name[16];
 strcpy(name, "Tessier-Lavigne");
 buggy_substring(name, 3, 2);
 printf("%s\n", name);
 return 0;
} 

为什么这会打印“Tessi”而不是“si”?这是将 size_t 与 char 混合的问题吗?

标签: cc-strings

解决方案


您只能在函数中更改起始位置。但是,在打印时,您仍然将字符串的原始头部传递给 printf。

尝试将 name+3 传递给 printf 。


    int main(int argc, char *argv[])
    {
     char name[16];
    // allocated a buffer of 16 bytes on the stack (called name)
    // note that an array of chars and a pointer to a char is NOT the same thing
     strcpy(name, "Tessier-Lavigne");
    // copies from a const null-terminated string 
    // now char* name contains
    // ['T','e','s','s','i','e','r','-','L','a','v','i','g','n','e','\0']
     buggy_substring(name, 3, 2);
    // name is passed as an immutable number "by value", 
    // the value of name is not changed
    // however, the contents name points to can be
    // now name is
    // ['T','e','s','s','\0','e','r','-','L','a','v','i','g','n','e','\0']


     printf("%s\n", name);
    //output 'T','e','s','s' + new line
     return 0;
    } 



    void buggy_substring(char *input, size_t pos, size_t len)
    {
    //local pointer input
    // points to ['T','e','s','s','i','e','r','-','L','a','v','i','g','n','e','\0']
    //pos=3
    //len=2
     input += pos;
    // input points to 's' (original name still points to 'T'

     input[len] = '\0';
    //equivalent code
     char * p=input;
     p+=len;
     *p='\0';
    // input+2 points to 'i'
    // 'i' is replaced with zero
    // the original buffer looks like
    //['T','e','s','s','\0','e','r','-','L','a','v','i','g','n','e','\0']
    } 

免责声明:当然,您应该将库字符串操作函数用于更严重的代码,并且不要尝试重新发明轮子。


推荐阅读