Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to swap arrays of arbitrary size in C++?
    primarykey
    data
    text
    <p>I'm wondering if it's possible to swap the contents of two C++ arrays that are of different sizes (without using any predefined C++ functions)? My code is as follows:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; void swapNames(char a[], char b[]) { //can be done with one temp; using two for clarity purposes char* temp = new char[80]; char* temp2 = new char[80]; int x = 0; while(*(b+x)!='\0') { *(temp+x) = *(b+x); x=x+1; } x=0; while(*(a+x)!='\0') { *(temp2+x) = *(a+x); x=x+1; } x=0; while(*(temp2+x)!='\0') { *(b+x) = *(temp2+x); x=x+1; } x=0; while(*(temp+x)!='\0') { *(a+x) = *(temp+x); x=x+1; } } int main() { char person1[] = "James"; char person2[] = "Sarah"; swapNames(person1, person2); cout &lt;&lt; endl &lt;&lt; "Swap names..." &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; "Person1 is now called " &lt;&lt; person1; cout &lt;&lt; "Person2 is now called " &lt;&lt; person2 &lt;&lt; endl;; } </code></pre> <p>My initial idea was to pass in references to person1 and person2 themselves, store the data in temp variables, delete the memory allocated to them, and link them to newly created arrays with the swapped data. I figured this would avoid predefined memory limits. It seems, though, that passing in references(&amp;) to arrays is very much not allowed.</p> <p>The above works fine if person1 and person2 are of the same size. However, once we have names of different sizes we run into problems. I assume this is because we can't alter the memory block we allocated when we initially created person1 and person2.</p> <p>Also, is it possible to create a new array in C++ without predefining the size? IE a way to create my temp variables without placing a limit on their sizes.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload