title: char array to a string inside a struct
body: <p>I have an array of 4 characters, for example:</p>
  
  <pre><code>char char_array[10];
  
  char_arr[0] = 'a';
  char_arr[1] = 'b';
  char_arr[2] = 'c';
  char_arr[3] = 'd';
  char_arr[4] = '\0';
  </code></pre>
  
  <p>and I have a structure:</p>
  
  <pre><code>typedef struct{
  int my_int;
  char *my_string;
  } my_struct_t;
  
  my_struct_t my_struct;  
  
  my_struct.my_string = malloc(10);
  </code></pre>
  
  <p>I want to assign the char array to the string <code>my_struct.my_string</code>
  How to I do this? I tried the following:</p>
  
  <h2>Attempt: 1</h2>
  
  <pre><code>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';
  </code></pre>
  
  <h2>Attempt: 2</h2>
  
  <pre><code>strcpy(my_struct.my_string, char_arr);
  </code></pre>
  
  <p>Both fail i.e the destination is empty (compilation succeeds). Why does the above fail and how can I overcome this?</p>
  
  <p>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 <code>my_struct.my_string</code> before assigning it.</p>