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;
}