C - 没有使用参数指针获得正确的值

cos*_*ost 2 c pointers function

get_current_path函数获取指向当前工作目录的char字符串的指针.printf("%s \n",buf); 在函数本身打印正是我想要的,但然后在函数外面,printf("%s",thisbuf); 给了我很多垃圾.我想我在这里犯了一些愚蠢的错误,但我无法弄清楚它是什么.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ela*_*fer 5

你应该传递一个指针 char *

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

int main()
{
    char *thisbuf;
    get_current_path(&thisbuf);
}
Run Code Online (Sandbox Code Playgroud)