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:
#include <iostream>
#include <string>
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 << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << "Person2 is now called " << person2 << endl;;
}
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(&) to arrays is very much not allowed.
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.
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.