c - Using malloc properly -


i'm trying put directory pathname on string variable, 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 blank printed, when 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 printed properly, why? isn't first malloc suppose make variable dir[512]

in

getcwd(dir, sizeof(*dir)) 

the sizeof producing 1 because *dir refers single char. isn't want. if replace 512, ought work fine.

the idiomatic coding 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 sizeof(*dir) no-op because returns 1. is, malloc allocates in units of char. i've omitted no-op.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -