简体   繁体   English

C中带指针的字符串串联

[英]String Concatenation in C with Pointers

So this is the standard string concatenation code in C: 因此,这是C中的标准字符串连接代码:

char *stringcat(char *dest, const char *src){
    char *save=dest;
    while(*save !='\0'){
        save++;
    }
    while(*src!='\0'){
        *save=*src;
        save++;
        src++;
    }
    *save='\0';
    return dest;
}

My question is why when we replace the first while loop with the following: 我的问题是为什么当我们用以下内容替换第一个while循环时:

while(*save++){};

It does not work, but, when replaced with: 它不起作用,但是当替换为:

while(*++save){};

It does work. 确实有效。 In the first two instances, save points to the null terminator at the end of dest at the end, which is then overwritten by the first character in src. 在前两个实例中,保存指向末尾dest处的空终止符,然后将其用src中的第一个字符覆盖。 However, in the third instance, it seems like save will be pointing to the character after the null terminator, which is weird. 但是,在第三种情况下,似乎save将指向空终止符之后的字符,这很奇怪。

while(*save++) 

First dereference save and compare that value to 0, then increment save. 首先解引用保存,然后将该值与0进行比较,然后递增保存。

while(*save !='\0'){
    save++;
}

First dereference save, compare to 0 and only increment if non-zero. 第一次解引用保存,与0比较,并且仅在非零时递增。 See the difference? 看到不同?

If you make it while (*save++) {} , the operation you are repeating is: load byte, increment pointer, check whether byte was zero. 如果while (*save++) {}时进行操作,则重复的操作是:加载字节,增量指针,检查字节是否为零。 Therefore, what will happen at the end of the string is: load null byte, increment pointer, check whether byte was zero, see it was, exit loop. 因此,在字符串末尾将发生的事情是:加载空字节,递增指针,检查字节是否为零,是否为零,退出循环。 So save will be pointing just after the null byte. 因此, save将指向空字节之后。 But you want to start copying the second string on top of that null byte, not after it. 但是,您想开始该空字节的顶部而不是在其之后复制第二个字符串。

(Is it possible that you have the meanings of ++save and save++ interchanged in your head? If so, here's a useful mnemonic: ++save means increment, then load the value; save++ means load the value, then increment. So the order in which the variable name and the ++ appear corresponds to the order of operations.) (是否有可能在您的头上互换了++savesave++的含义?如果这样,这是一个有用的助记符: ++save表示递增,然后加载值; save++表示加载值,然后递增。因此变量名称和++出现的顺序与操作顺序相对应。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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