c - Pointer to a stack allocated char array -


i have array stack allocated , used hold error messages. in cases call function returns error code , based on code know add array, use simple array:

char buf[1024]; 

now have function can return error code or can provide "results." in case array holds results allocated elsewhere , there no reason copy 1 array other want use pointer array , pass around. way, if function returns without error, buf ready consumed. this:

char _buf[1024]; char **buf = &_buf; 

obviously won't work because types wrong. casting char** compiles (fwiw, i'm using gcc -std=c99 -w -wall -g -gdb) segfault when try use *buf.

char _buf[1024]; char **buf = (char**)&_buf; 

the current solution have using intermediate variable seems want in round way:

char _buf[1024]; char *tmp = _buf; char **buf = &tmp; 

so, question is: there more appropriate way accomplish these 3 lines?

assuming means think does:

now have function can return error code or can provide "results."

your function accepts address of char* populated dynamic results on success, hosts as-input address of error message buffer populate in event of failure, , caller responsible of discerning appropriate action take based on result of function (success means free results later, failure means caller-provided input buffer has error message.

if accurate, you're wanting:

#include <stdio.h> #include <stdlib.h> #include <string.h>   // function fails when param less 0 int some_action(int param, char **res) {     if (param < 0)     {         if (*res)             sprintf(*res, "param = %d", param);         return -1;     }      *res = strdup("success data here");     return 0; }   int main() {     int i=0;      (i=-2; i<2; ++i)     {         char errmsg[1024] = "";         char *res = errmsg;          if (some_action(i, &res) == 0)         {             printf("success: %s\n", res);             free(res);         }         else         {   // error (no free needed)             printf("error: %s\n", res);         }     }      return 0; } 

output

error: param = -2 error: param = -1 success: success data here success: success data here 

note: don't particularly advise approach you're not saving anything in long run unless you're expecting significant number of errors, should exception rather norm. furthermore, if still consider doing strongly advise provide error buffer length data action function , utilize ensure safety against possible buffer overflow. (i have done it, gotta something here).


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -