title: string copy routine does not work in C
body: <p>I tried the below code to copy a string in C but I am not getting the correct result.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void){
      char *string1;
      char *string2 = "abcdefghijk";
      char *ptr = string2;
      unsigned int no_of_chars =0;
  
      while(*ptr++ !='\0'){
          no_of_chars++;
      }
  
      string1 = malloc(sizeof(char)*(no_of_chars+1));
      while(*string1++ = *string2++);
      printf("string2=%s\n",string2);
      printf("string1=%s\n",string1);
  
      return 0;  
  }
  </code></pre>
  
  <p>I am getting the below result using the MinGW compiler:</p>
  
  <pre><code>string2=string2=%s
  </code></pre>
  
  <h2>    string1=ï‼</h2>
  
  <p>edit : Okay Changed the code and below code works.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void){
      char *string1;
      char *string2 = "abcdefghijk";
      char *ptr = string2, *ptrsrc = string2;
      unsigned int no_of_chars = 0;
  
      while(*ptr++ !='\0'){
          no_of_chars++;
      }
  
      char *ptrdst = string1 = malloc(sizeof(char)*(no_of_chars+1));
  
      while(*ptrdst++ = *ptrsrc++);
  
      printf("string2=%s\n",string2);
      printf("string1=%s\n",string1);
  
      return 0;   
  }
  </code></pre>