I have created this very simple program. My goal is to have the output say String: hello world James
but I want the hello world to be malloced in my test_function
. Can someone explain to me how I can make my_intro = "hello world"
and name my_name = "James"
. This problem is revolves around how I can parse the malloc-ed char value back to my main function. This is not a duplicate of changing ints. This is parsing char *
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test_function(char *a_intro, char *a_name);
int main(void) {
char *my_intro;
char *my_name;
test_function(my_intro, my_name);
printf("String: %s %s\n", my_intro, my_name);
}
void test_function(char *a_intro, char *a_name) {
char *intro = malloc(20);
char *name = malloc(20);
strcpy(intro, "hello world");
strcpy(name, "James");
a_intro = intro;
a_name = name;
}
But the error I get is:
testcode.c: In function 'main':
testcode.c:10:5: error: 'my_intro' is used uninitialized in this function [-Werr
or=uninitialized]
test_function(my_intro, my_name);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
testcode.c:10:5: error: 'my_name' is used uninitialized in this function [-Werro
r=uninitialized]
cc1.exe: all warnings being treated as errors
Another possible solution which doesn't work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test_function(char *a_intro, char *a_name);
int main(void) {
char *my_intro;
char *my_name;
test_function(&my_intro, &my_name);
printf("String: %s %s\n", my_intro, my_name);
}
void test_function(char *a_intro, char *a_name) {
char *intro = malloc(20);
char *name = malloc(20);
strcpy(intro, "hello world");
strcpy(name, "James");
*a_intro = intro;
*a_name = name;
}
Error:
testcode.c: In function 'main':
testcode.c:10:19: error: passing argument 1 of 'test_function' from incompatible
pointer type [-Werror=incompatible-pointer-types]
test_function(&my_intro, &my_name);
^
testcode.c:5:6: note: expected 'char *' but argument is of type 'char **'
void test_function(char *a_intro, char *a_name);
^~~~~~~~~~~~~
testcode.c:10:30: error: passing argument 2 of 'test_function' from incompatible
pointer type [-Werror=incompatible-pointer-types]
test_function(&my_intro, &my_name);
^
testcode.c:5:6: note: expected 'char *' but argument is of type 'char **'
void test_function(char *a_intro, char *a_name);
^~~~~~~~~~~~~
testcode.c: In function 'test_function':
testcode.c:22:14: error: assignment makes integer from pointer without a cast [-
Werror=int-conversion]
*a_intro = intro;
^
testcode.c:23:13: error: assignment makes integer from pointer without a cast [-
Werror=int-conversion]
*a_name = name;
^
cc1.exe: all warnings being treated as errors