C-使用参数指针无法获取正确的值

C-使用参数指针无法获取正确的值,c,function,pointers,C,Function,Pointers,get_current_path函数获取指向当前工作目录的字符字符串的指针。printf(“%s\n”,buf);在函数本身中,打印出我想要的内容,但在函数外部,打印F(“%s”,thisbuf);给了我很多垃圾。我想我犯了一些愚蠢的错误,但我不知道是什么 #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> int get_current_

get_current_path函数获取指向当前工作目录的字符字符串的指针。printf(“%s\n”,buf);在函数本身中,打印出我想要的内容,但在函数外部,打印F(“%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;
}
#包括
#包括
#包括
#包括
int获取当前路径(char*buf){
长cwd_尺寸;
char*ptr;
cwd_size=pathconf(“.”,_PC_PATH_MAX);
if((buf=(char*)malloc((size\u t)cwd\u size))!=NULL)
ptr=getcwd(buf,(size_t)cwd_size);
否则cwd_大小==-1;
printf(“%s\n”,buf);
printf(“%ld\n”,cwd\U大小);
返回cwd_大小;
}
int main(int argc,字符**argv)
{
char*thisbuf;
获取当前路径(thisbuf);
printf(“%s”,thisbuf);
返回0;
}

您应该将指针传递给
char*

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

int main()
{
    char *thisbuf;
    get_current_path(&thisbuf);
}
请尝试以下方法:

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


您试图传递buf的副本以获取当前路径,因此在修改buf时,指向buf的原始指针未被修改。

C中的参数是按值传递的,这意味着
获取当前路径
无法更改调用者传入的“thisbuf”的值

要进行更改,必须传入指向“thisbuf”的指针:

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

    return 0;
}
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"