c - What is the bestway to return a char pointer? -
what best way return or pass strings in char pointers in c?
i have function looks this:
char *test_getcwd(){ char *cwd; char *ret; if ((cwd = getcwd( ret, pathconf(".",_pc_path_max) )) == null){ perror ( "error on calling getcwd() function" ); }else if (__include_level__ == 0){ puts( cwd ); } free( cwd ); return ret; }
should change to:
int test_getcwd(const **pass){ char *cwd; char *ret; if ((cwd = getcwd( ret, pathconf(".",_pc_path_max) )) == null){ perror ( "error on calling getcwd() function" ); }else if (__include_level__ == 0){ puts( cwd ); } free( cwd ); *pass = ret; return 0; }
or leave or maybe change else?
similar questions may have been asked goal find best practice it.
the first argument getcwd
must either null or pointer existing buffer. clue how design routine. either:
- accept pointer existing buffer parameter, , accept size, , pass
getcwd
or - pass null
getcwd
.
in either case, return pointer same way getcwd
does. requiring caller pass pointer set unnecessarily complicated. not it, on principle of keeping things simple.
in first case, reason return pointer indicate whether error occurred. when error not occur, caller knows buffer is, since passed routine.
your code shows confusion uses of ret
, cwd
. if value passed getcwd
in ret
not null, same value returned , assigned cwd
. cannot both free pointer , return caller used. consider this:
char *test_getcwd() { char *ret = getcwd(null, ps_test_pathconf(".",_pc_path_max)); if (ret == null) perror("klaida iškvietus getcwd() funkciją"); else if (__include_level__ == 0) puts(ret); return ret; }
Comments
Post a Comment