> Swapping Null terminated C strings help?

Swapping Null terminated C strings help?

Posted at: 2014-12-18 
Wait, what?

You are trying to put the contents of name2, which is has sizeof 6, into name, which has sizeof 4? You can't do that. It isn't going to fit. You can't put 6 chars into a 4 char array. (Well....actually, in C/C++, you can. But the end result is undefined. It might appear to work, but it is wrong, and can fail in all sorts of unpredictable ways).

I suspect you are reading the homework question wrong. You can't swap C style strings if they aren't the same size. The language doesn't allow it.

Read the question again.

So I'm trying to write a program that swaps Null terminated C strings. I'm not supposed to use pointers, a third array, and only one loop. I've been stuck on this for a while now. If anyone could help point the way I would be very appreciative.

This is what I have so far.

#include

using namespace std;

int main()

{

char name[4] = {'A', 'b', 'e', '\0'};

char name2[6] = {'R', 'o', 'b', 'i', 'n', '\0'};

char temp;

for(int i =0; i == '\0'; i++)

{

temp=name[i];

name[i]=name2[i];

name2[i]=temp;

}

//To read results

for(int i =0; i < 6; i++)

{

cout << name2[i];

}

}

Thanks in advance. I hope everyone has a great night!