繁体   English   中英

C中使用指针的字符串连接

[英]String concatenation using pointers in C

我在此代码中将一个字符串 (t) 连接到另一个字符串 (s) 的末尾,但一直使用运算符及其在循环中的优先级 ( while() )

1.while while(*s++); 不做工作

2.while while(*s) ++s;

但是它们之间有什么区别呢?

#include<stdio.h>
void strcat(char *, const char *);

int main(void){
    char s[100] = "Aditya ";
    char t[100] = "Kumar";
    strcat(s, t);
    printf("%s ", s);
    return 0;
}

void strcat(char * s, const char * t){
    while(*s)
        s++;

    while(*s++ = *t++);
}

为什么在 strcat() 函数中首先 while while(*s++); 不连接字符串,而是连接while(*s) s++; 我猜他们的工作方式是一样的吗?

它们不是等价的。

while(*s++);

无论如何都会增加指针,所以当*s\\0 ,指针会再次增加。 连接发生空终止符之后。 缓冲区的其余部分包含零,因此它不会崩溃,但不会完成工作。

while(*s) { s++; }

*s\\0时停止。 所以没有执行额外的增量。

暂无
暂无

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

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