my original problem is that I want to write a function that can return me two values. I know that I can do it by passing the address of the two arguments to the function, and directly calculate their values inside that function. But when doing experiment, something weird happens. The value I got inside the function cannot survive to the main function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void build(char *ch){
ch = malloc(30*sizeof(char));
strcpy(ch, "I am a good guy");
}
void main(){
char *cm;
build(cm);
printf("%s\n", cm);
}
The above program just prints out some garbage. So I want to know what's wrong here. Eventually, I want something like this parse(char **argv, char **cmd1, char **cmd2), which can parse out two commands for me from the original command argv. That would be great if anybody can explain a little bit. Thanks a lot.
char **ch......*ch = malloc......strcpy(*ch......build(&cm)...nand said function wants to assign a new value ton(n = ...) then a level of indirection is required, i.e., you need a pointer ton(typeof_n*). All function arguments in C are passed by value, i.e., a copy is made. So, since you pass in achar*, you need a pointer to one of those, i.e., achar**. Then you can write*n = malloc(size);. Also,sizeof charis defined to be1, so no need for that in yourmalloccall.