title: C++ strcpy pointers that are passed to a function
body: <p>I am passing an string or a char array to a function and swapping them but losing the first char array's value for some reason.  Here is my code:</p>
  
  <pre><code>void foo(char* a, char* b){
  
           char* temp;
  
           temp = new char[strlen(a)+1];
           strcpy(temp, a);
           strcpy(a, b);
           strcpy(b, temp);
  
           delete[] temp;
  }
  </code></pre>
  
  <p>So in foo the function gets passed two pointers and the are attempted to be swapped.
  Here is the main function. There may be a problem with the passing of the variable, but the compiler did not give me an issue.</p>
  
  <pre><code>int main(){
  
           char a[] = "First";
           char b[] = "Last";
  
           std::cout &lt;&lt; "A Before: "&lt;&lt; a &lt;&lt; "\n";
           std::cout &lt;&lt; "B Before: " &lt;&lt; b &lt;&lt; "\n\n";
  
           foo(a, b);
  
           std::cout &lt;&lt; "A After: "&lt;&lt; a &lt;&lt; "\n";
           std::cout &lt;&lt; "B After: "&lt;&lt; b &lt;&lt; "\n\n";
  
           return 0;
  }
  </code></pre>
  
  <p>The output I am getting is as follows:</p>
  
  <pre><code>A Before: first
  B Before: last
  
  A After: 
  B After: first
  </code></pre>
  
  <p>Now I have tested the values of the strings while in the function during the strcpy's and turns empty after the final strcpy, which means, or at lest I think, that the problem lies within the pointers to the original variables. It could be a chain reaction type of thing where all of the pointers are pointing to the "a" and it confuses the program.  </p>
  
  <p>Any help would be appreciated, also why this is happening would be very useful as well. </p>