簡體   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