Reputation: 671
How do I (m)allocate string in another function? I've tried to do it by 2 ways (down in code JUST EXAMPLE - I wouldn't do it with argv).
void someFunction(char* string, char** argv) {
string = (char*)malloc(strlen(argv[2]) + 1);
strcpy(string,argv[2]);
// string[strlen(argv[2]) + 1] = '\0' //should I do this now?
printf("%s",string); //outputs string (works fine)
}
int main(int argc, char** argv) {
char *string;
char *string2;
someFunction(string,argv);
printf("%s",string); //outputs (null)
free(string);
someFunction(&*string2,argv);
printf("%s",string2); //outputs (null)
free(string2);
}
I want to use "string" in main, but mallocate it in different function.
Thank you!
Upvotes: 1
Views: 908
Reputation: 121649
Here are two examples:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void alloc1 (char **new_string, char *text) {
*new_string = malloc(strlen(text)+1);
strcpy (*new_string, text);
}
char * alloc2(char *text) {
char *new_string = malloc(strlen(text)+1);
strcpy (new_string, text);
return new_string;
}
int
main (int argc, char *argv[]) {
char *s;
/* Make sure we entered a command line argument */
if (argc < 2) {
printf ("USAGE: myprog SOMETHING\n");
return 1;
}
alloc1(&s, argv[1]);
printf ("alloc1: s=%s\n", s);
free (s);
s = alloc2 (argv[1]);
printf ("alloc2: s=%s\n", s);
free (s);
return 0;
}
The first example passes a pointer to a pointer: your main allocates the pointer; the function allocates the space to the pointer; the pointer itself is passed by reference.
The second example is similar, except the pointer is returned by the function instead of altering the reference.
The first is "cleaner" if you're only initializing one pointer; the second is useful if you want to return multiple different values in the same function.
Upvotes: 4
Reputation: 50775
You want this:
void someFunction(char** string, char** argv) {
*string = (char*)malloc(strlen(argv[2]) + 1);
strcpy(*string, argv[2]);
// string[strlen(argv[2]) + 1] = '\0' //should I do this now?
printf("%s",*string); //outputs string (works fine)
}
int main(int argc, char** argv) {
char *string;
char *string2;
someFunction(&string,argv);
printf("%s",string);
free(string);
}
Upvotes: 2