I'm trying to put my directory pathname on a string variable, like this:
int main(int ac, char **av)
{
char*dir;
if(ac > 2)
{
dir = malloc(sizeof(*dir) * 512);
getcwd(dir, sizeof(*dir));
printf("dat dir is:\n");
printf("%s\n", dir);
}
}
I got a blank printed, but when I do something like that
int main(int ac, char **av)
{
char dir[512];
if(ac > 2)
{
// dir = malloc(sizeof(dir) * 512);
getcwd(dir, sizeof(dir));
printf("dat dir is:\n");
printf("%s\n", dir);
}
}
it is printed properly, why? Isn't my first malloc suppose to make my variable like dir[512]
In
getcwd(dir, sizeof(*dir))
the sizeof
is producing a 1 because *dir
refers to a single char
. This isn't what you want. If you replace this with 512, all ought to work fine.
The idiomatic coding would be something like this:
int main(int ac, char **av)
{
const int buf_size = 512;
char *dir;
if(ac > 2)
{
dir = malloc(buf_size);
getcwd(dir, buf_size);
printf("dat dir is:\n");
printf("%s\n", dir);
}
}
Note multiplying by sizeof(*dir)
is a no-op because it always returns 1. That is, malloc
allocates in units of char
. So I've omitted the no-op.