2012-09-16 43 views
0

我想更改函數中變量的值。 我的代碼是這樣的:更改函數中指針的值

void change(char *buf){ 
    char str = "xxxxxxx"; 
    *buf = &str; 
} 
int main(){ 
    char *xxx = NULL; 
    change(xxx); 
} 

,當我和Valgrind的調試,它說:

==3709== Invalid write of size 1 
==3709== at 0x80483CA: change (test.c:5) 
==3709== by 0x80483E5: main (test.c:10) 
==3709== Address 0x0 is not stack'd, malloc'd or (recently) free'd 
==3709== 
==3709== 
==3709== Process terminating with default action of signal 11 (SIGSEGV) 
==3709== Access not within mapped region at address 0x0 
==3709== at 0x80483CA: change (test.c:5) 
==3709== by 0x80483E5: main (test.c:10) 

誰能幫助我?我用C是新....

+0

有什麼毛病,幾乎每行......請閱讀更多的指針和指針語法。 – nneonneo

+0

在撰寫此問題之前,您未能啓用並關注編譯器警告。請不要這樣做。 –

回答

4

使用指針的指針:

void change(char **buf) 
{ 
    *buf = "xxxxxxx"; 
} 

int main(void) 
{ 
    char *xxx = NULL; 
    change(&xxx); 
} 
+1

應該注意,這種方法是有效的,因爲正在使用字符串文字,它通過可執行文件的數據段全局分配一個內存地址,所以指針在離開函數範圍時保持有效。它可能無法在其他一些字符串範圍內工作(可能是臨時的或在本地範圍內動態創建的)。 –