当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - Printing Present working directory in c using pointers

问题描述:

Aim : Print present working directory in c on Linux machine.

Without using pointers, it is giving correct output..

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

}

But with pointer it shows following error

getcwd() error : : Numerical result out of range

网友答案:

This is because when buf is a pointer, sizeof(buf) is the number of bytes required to store a pointer, not the size of the array, as in the code that you commented out.

You need to pass the size that you allocated (i.e. 1024) instead, like this:

size_t allocSize = sizeof(char) * 1024;
buf = (char *)malloc(allocSize);
if((cwd = getcwd(buf, allocSize)) != NULL) ...
网友答案:

sizeof(buf) will return the size of char* which will be however many bits wide your processor is (32 bits or 64 bits).

What you want is to use the magic number you malloc'ed with, in this case 1024.

Try this:

#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);
Here you are giving the size as sizeof(buf) which will return the size of the buf pointer which will be machine dependent.
You have to specify 1024 in the argument to getcwd.

分享给朋友:
您可能感兴趣的文章:
随机阅读: