2016-12-01 90 views
-1

我正在寫一個簡單的字符串替換函數,我有一個相當有趣的錯誤。不應該strcpy只是覆蓋buf \ streamBuf值?它如何連接數組?意外的行爲與strcpy和數組

int main() 
{ 
    char buf[512]; 
    strcpy(buf, "Test\nInput\nHere\n"); 

    char fromCh[2] = "\n"; 
    char toCh[4] = "\\n "; 
    stripChars(buf, fromCh, toCh); 
    printf("Here's your buf: %s", buf); 
    return 0; 
} 

void stripChars(char *streamBuf, char* fromCh, char *toCh){ 
     char strTemp[512]; 
     int i=0; 
     int iLenFrom = strlen (fromCh); 
     int iLenTo = strlen (toCh); 
     while (*streamBuf) 
     { 
      if (strncmp (streamBuf, fromCh, iLenFrom) == 0) 
      { 
       strncpy (&(strTemp[i]), toCh, iLenTo); 
       i += iLenTo; 
       streamBuf += iLenFrom; 
      } 
      else 
      { 
       strTemp[i++] = *streamBuf; 
       streamBuf++; 
      } 
     } 
    strTemp[i] = '\0'; 
    strcpy(streamBuf, strTemp); 

    printf("Here's your strTemp: %s \n", strTemp); 
    printf("Here's your streamBuf: %s \n", streamBuf); 
} 

,這裏是我的輸出

Here's your strTemp: Test\n Input\n Here\n 
Here's your streamBuf: Test\n Input\n Here\n 
Here's your buf: Test 
Input 
Here 
Test\n Input\n Here\n 
Process finished with exit code 0 
+0

函數:'stripChars()'缺少所需的原型。應該將原型插入文件頂部附近。 – user3629249

回答

3

爲什麼它加到陣列?

這是因爲你正在改變streamBuf指向函數的位置。

跟蹤streamBuf所指向的原始位置,並在函數結束時使用它。

void stripChars(char *streamBuf, char* fromCh, char *toCh) 
{ 
    char* originalPointer = streamBuf; 

    ... 

    streamBuf = originalPointer; 
    strcpy(streamBuf, strTemp); 

    printf("Here's your strTemp: %s \n", strTemp); 
    printf("Here's your streamBuf: %s \n", streamBuf); 
} 
3

這裏

streamBuf += iLenFrom; 

這裏

streamBuf++; 

你改變streamBuf

因此它將不再等於main中的buf

所以對數據的更改指向streamBuf不再相同,變化的數據指向buf

如果你想看看會發生什麼,你可以添加指針值的印刷品,如:

printf("buf is at %p\n", (void*)buf); 
stripChars(buf, fromCh, toCh); 

void stripChars(char *streamBuf, char* fromCh, char *toCh){ 
    printf("streamBuf is at %p\n", (void*)streamBuf); 
    .... 
    .... 
    printf("streamBuf is at %p\n", (void*)streamBuf); 
    printf("Here's your streamBuf: %s \n", streamBuf); 
} 
+0

謝謝!我沒有注意到它是愚蠢的。 – Oreols