I have these methods.
I have defined a char array in stringcontent.h file and that array is taken from a method in another filetest.c.
// stringcontent.h
char content1[] = "blahblah";
void get_char_array(int which,char *buffer){
if(which == 1)
buffer = content1;
printf("%s",buffer); // prints : "blahblah"
// and so on.....
}
// test.c
#include "stringcontent.h"
main(){
char *buf;
get_char_array(1,buf);
printf("%s",buf); // prints rubbish rubbish !!!
}
I have to stick to this method interface(function signatures) and how can I fix this?
If I understand, you want to get the variable using the function get_char_array. Then If I understand you need to do the following (change the get_char_function to receive a pointer to pointer to a char):
EDIT:
Put your declarations in the header file and implementation in the “.c” or you will have linker errors.
To compile (if using gcc):
Note you don’t need to “export”
content1since the only thing you need, a pointer, is returned by a function.Here is another solution using strcpy. In this case you don’t need to pass a pointer to pointer.
In this case you have to take care to allocate sufficient size in buf before call the get_char_array.
I prefer the first solution, it doesn’t need to use the strcpy. And if you don’t allocate sufficient space in the buf you can have problems. One solution is to pass the size of the buf in the function and check it before strcpy or use strncpy.