2016-02-16 65 views
-6

我有一個函數,它將char *strconst char a作爲參數,並將*str中的每個單獨的a更改爲'X'。因爲我無法修改值指針點,如*str = 'X'。我如何去解決這個問題?如何更改指針的值C

+3

爲什麼說你不能執行'* str ='X''? – psmears

+0

調用該函數的代碼應確保通過可變緩衝區 –

+0

您可能會發現http://stackoverflow.com/questions/2229498/passing-by-reference-in-c有幫助。 – stonemetal

回答

0

讓我們假設我們有這樣的功能:

int change_char(char *str, const char a, const char b) { 
    int n = 0; 
    if (str) { 
     while (*str) { 
      if (*str == a) { 
       *str = b; // Can I modify the value pointed by the pointer? 
       ++n; 
      } 
     ++str; // Can I modify the pointer? 
     } 
    } 
    return n; 
} 

當我們調用該函數,如下面的示例中,指針是按值傳遞的,所以你不能修改原始指針(只它的本地副本),但您可以修改該指針指向的對象的值:

char test[] = "Hello world!"; 
change_char(test, 'o', 'X'); 
printf("%s\n",test); // it will output HellX wXrld! 
+0

我在原始測試中使用了char * tset =「Hello world」。結果我每次運行它時都會得到相同的字符串。你能解釋一下更具體的差異嗎?謝謝! –

+0

@KevinWei'「Hello world」'是一個常量字符串文字,你可以用'char test [] =「Hello world!」來初始化一個以null結尾的字符串;'然後修改它中的字符,但是如果你聲明一個像char * test =「Hello world」這樣的指針,它將指向一個costant,並且任何修改這個chars的嘗試都會導致運行時錯誤。在這種情況下,您應該分配內存然後複製字符串。看一個實例[這裏](https://ideone.com/0dlUAJ)。 –