c - 使用指针在 c 中打印当前工作目录

标签 c linux pwd

目标:在 Linux 机器上以 c 打印当前工作目录。

不使用指针,它给出正确的输出..

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, sizeof(buf))) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

但是用指针显示如下错误

getcwd() error : : Numerical result out of range

最佳答案

这是因为当buf是一个指针时,sizeof(buf)是存储一个指针所需的字节数,而不是数组的大小,如您注释掉的代码中所示。

您需要传递分配的大小(即 1024),如下所示:

size_t allocSize = sizeof(char) * 1024;
buf = (char *)malloc(allocSize);
if((cwd = getcwd(buf, allocSize)) != NULL) ...

关于c - 使用指针在 c 中打印当前工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9697056/

相关文章:

c - libxml2 将节点及其所有内容转换为原始 xml 字符串

c - 设置 GTK 容器子级的属性

c++ - open() 中的正确路径

c - 如何在 Linux 中使用 gethostbyname_r

c++ - 了解qmake工程文件中的Term\\\"$$PWD/\\\"

c - C语言中的位选择

linux - gcc 错误 - "error adding symbols: DSO missing from command line"

linux - Git 平均备份时间是多少

python - 如何在开发机器上强制 ImportError? (密码模块)

unix - shell 内置 pwd 与/bin/pwd