I have an array of 4 characters, for example:
char char_array[10];
char_arr[0] = 'a';
char_arr[1] = 'b';
char_arr[2] = 'c';
char_arr[3] = 'd';
char_arr[4] = '\0';
and I have a structure:
typedef struct{
int my_int;
char *my_string;
} my_struct_t;
my_struct_t my_struct;
my_struct.my_string = malloc(10);
I want to assign the char array to the string my_struct.my_string
How to I do this? I tried the following:
Attempt: 1
my_struct.my_string = malloc(10)
my_struct.my_string[0] = char_arr[2];
my_struct.my_string[1] = char_arr[2];
my_struct.my_string[2] = '\0';
Attempt: 2
strcpy(my_struct.my_string, char_arr);
Both fail i.e the destination is empty (compilation succeeds). Why does the above fail and how can I overcome this?
I have both the struct and the char array in stack since I don’t want these once I exit the function. I have allocated memory to my_struct.my_string before assigning it.
You can do it two ways:
Assign the pointer to the character array
Once the function exits the char_array[10] which the pointer points to will become invalid. The compiler will produce no error, but eventually the program will likely crash because you will overwrite data for another function, or read the wrong data because another function overwrote it with something else. You should google about how the stack works on your computer architecture.
Allocate memory and copy the character array
I used for loops to help make it easier to understand exactly how it works. Once the current function exits the pointer will still point to valid memory if you happen to keep it around somehow.