目的 :在 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) ...

其他提示

sizeof(buf)将返回世代odicetagcode的大小,但是处理器的许多位宽(32位或64位)。

您想要的是使用Malloc的Magic号码,在这种情况下,在这种情况下1024。

试试:

#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, 1024)) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}
.

char *getcwd(char *buf, size_t size);
这里你给出的尺寸为 sizeof(buf) 这将返回的大小 buf 与机器相关的指针。
您必须在参数中指定 1024 getcwd.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top