I have an array that is stack allocated and used to hold error messages. In most cases i call a function that returns an error code and based on that code i know what to add to the array, so i use a simple array:
char buf[1024];
Now I have a function that can return an error code or can provide some "results." In this case the array that holds the results is allocated elsewhere and there is no reason to copy from one array to the other so i really want to use a pointer to an array and pass that around. This way, if the function returns without error, then buf is ready to be consumed. So something like this:
char _buf[1024];
char **buf = &_buf;
Obviously this won't work because the types are wrong. Casting to a char** compiles (FWIW, I'm using gcc -std=c99 -W -Wall -g -gdb) but will segfault when I try to use *buf.
char _buf[1024];
char **buf = (char**)&_buf;
The current solution that I have is using an intermediate variable but this just seems to do what I want in a round about way:
char _buf[1024];
char *tmp = _buf;
char **buf = &tmp;
So, my question is: Is there a more appropriate way to accomplish these three lines?
char **as a pointer to a char array, which is wrong. Usechar *instead.char*to receive a dynamic allocation upon "success" that is later caller-responsible for free'ing , while utilizing said-same output parameter to host a caller-provided address of an error message buffer to populate in the event of "failure". Is that accurate?-Wall -Wextra, and handle all warnings appropriately.