2011-01-27 72 views
2

get_current_path函數獲取指向當前工作目錄的char字符串的指針。 printf(「%s \ n」,buf);在函數本身打印什麼我想要的,但是然後在函數外,printf(「%s」,thisbuf);給了我很多垃圾。我認爲我在這裏犯了一些愚蠢的錯誤,但我無法弄清楚它是什麼。C - 沒有通過參數指針獲取正確的值

#include <stdio.h> 
#include <stdlib.h> 
#include <strings.h> 
#include <unistd.h> 

int get_current_path(char *buf) { 
long cwd_size; 
char *ptr; 

cwd_size = pathconf(".", _PC_PATH_MAX); 


if ((buf = (char *) malloc((size_t) cwd_size)) != NULL) 
    ptr = getcwd(buf, (size_t)cwd_size); 
else cwd_size == -1; 

printf("%s\n", buf); 
printf("%ld\n", cwd_size); 
return cwd_size; 
} 


int main (int argc, char **argv) 
{ 
char *thisbuf; 
get_current_path(thisbuf); 
printf("%s", thisbuf); 

return 0; 
} 

回答

4

C中的參數是按值傳遞的,這意味着get_current_path不能更改調用者傳入的「thisbuf」的值。

要做出改變,你會在一個指向「thisbuf」經過:

int get_current_path(char **resultBuf) { 
    char *buf = (char *) malloc((size_t) cwd_size); 
    ... 
    *resultBuf = buf; // changes "thisbuf" in the caller 
} 
.... 

get_current_path(&thisbuf); // note - passing pointer to "thisbuf" 
5

你應該通過一個指針char *

int get_current_path(char **buf) 
{ 
    *buf = ...; 
} 

int main() 
{ 
    char *thisbuf; 
    get_current_path(&thisbuf); 
} 
4

試試這個:

int get_current_path(char **buf) { 
*buf = something; // Set buf with indirection now. 

和:

int main (int argc, char **argv) 
{ 
    char *thisbuf; 
    get_current_path(&thisbuf); 
    printf("%s", thisbuf); 

    return 0; 
} 

你試圖傳遞一個副本 buf到get_current_path,所以當buf被修改時,指向buf的原始指針沒有被修改。