2017-02-23 161 views
0

我試圖指揮strncat功能。我理解它的大部分內容,可以用差異的方式來寫,但我無法弄清楚如何編寫更長版本的while (!(*dest++ = *src++))C if((!(* dest ++ = * srC++))return ret是什麼意思?

char *_strncat(char *dest, char *src, int n) 
{ 
    char *ret = dest; 
    while (*dest) /* same as: while (dest[0] !- '\0') */ 
    { 
     dest++; /* w. each loop, array is shifted left until it's empty */ 
    } 
    while (n != 0) 
    { 
     if (!(*dest++ = *src++)) /* <=========here */ 
      return ret; 
     n--; 
    } 
    *dest = 0; 
    return (ret); 
} 

有人可以展示和解釋如何擴展該行,以便我可以指導它並瞭解它是如何工作的?謝謝!

+0

= or ==?我認爲你在那裏有一個錯誤? –

+4

@TonyTannous不,這是故意的。該代碼正在尋找空終止符 –

+0

空的反向爲真 –

回答

2

行:

if (!(*dest++ = *src++)) 
    return; 

可擴展到:

char temp1 = *src++; // copy from *src to temp1 and increment src 
char temp2 = (*dest++ = temp1); // Copy temp1 to *dest, increment dest, and also copy value to temp2 
if (!temp2) return ret; // return if the value that was copied is a null byte 

使用後遞增是很重要的位置。它確保我們在指針遞增之前從*src複製到*dest。因此,要進一步擴大它,這將是:

char temp1 = *src; 
src = src + 1; 
char temp2 = (*dest = temp1); 
dest = dest + 1; 
if (!temp2) 
    return ret; 
+0

我認爲後增量部分應該擴大,因爲它讓我感到最困惑,因爲我懷疑。 –

+0

@Barmar謝謝!我正在通過這個工作。當我點擊'char temp2 =(dest = temp1);'它返回'錯誤:賦值使整型指針沒有強制轉換[-Werror = int-conversion] char temp2 =(dest = temp1);' – dbconfession

+0

@dbconfession change該行爲:'char temp2 =(* dest = temp1);' –

1

基本上它是複製的src值放入dest,遞增,然後空檢查(或空終止)。所以,你可以擴展它是這樣的:

*dest = *src; // Copy the value 
if (*dest == '\0') // Was it null? 
    return; // We are done! 
dest++; // go to next character 
src++; // go to next character 

一個混亂的點可能因使用了=的,而不是一個==到來。該=操作始終返回已分配的值,這使得分配的菊花鏈:

int a, b, c; 
a = b = 0; // sets both a and b to 0 
if (c = a) // sets c = a, then performs if(0) which is false. 

注: 技術上的srcdest指針遞增,即使在復位的情況下,因此這將正確擴展到下面,但這只是噪聲,以瞭解代碼在做什麼:

*dest = *src; // Copy the value 
if (*dest == '\0') // Was it null? 
{ 
    dest++; // not really needed but happens 
    src++; // not really needed but happens 
    return; // We are done! 
} 
dest++; // go to next character 
src++; // go to next character 
+1

除了'dest ++'和'srC++'仍然發生,即使發生'return'。 –

+0

所以你是正確的,src和dest在這種情況下會遞增,但就算法而言(或者理解算法的工作原理),這是一個有爭議的問題。但我對這個發現印象深刻!我更新了答案。 –