build()
take the pointer ch
by value, i.e. a copy of the pointer is passed to the function. So any modifications you make to that value are lost when the function exits. Since you want your modification to the pointer to be visible in the caller's context, you need to pass a pointer to pointer.
void build(char **ch){
*ch = malloc(30*sizeof(char));
strcpy(*ch, "I am a good guy");
}
Also, you don't need to pass pointers to a function because you need to return multiple values. Another option is to create a struct
that contains the values you wish to return as members, and then return an instance of said struct
. I'd recommend this approach over the first if the values are related and it makes sense to package them together.
Here's a re-listing of your code after fixing bugs:
#include
#include
#include
void build(char **ch){
*ch = malloc(30 * sizeof(char));
strcpy(*ch, "I am a good guy");
}
int main() { // main must return int
char *cm;
build(&cm); // pass pointer to pointer
printf("%s\n", cm);
free(cm); // free allocated memory
return 0; // main's return value, not required C99 onward
}