Reputation: 3
I'm trying to do a C-style string copy but something is not working right. What am I doing wrong?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char string_a[20]="Good day!";
char string_b[30]="Hi!";
int i=0;
cout << "string a: " << string_a << endl;
cout << "string b: " << string_b << endl;
while (*string_a++ = *string_b++) {
cout << ++i << endl;
}
cout << "string a: " << string_a << endl;
cout << "string b: " << string_b << endl;
return 0;
}
Upvotes: 0
Views: 793
Reputation: 882606
You cannot do:
string_a++
if string_a
is defined as an array. That only works for pointers and arrays decay to pointers only in specific circumstances.
If you change:
while (*string_a++ = *string_b++) {
cout << ++i << endl;
}
into:
char *pa = string_a, *pb = string_b; // a "specific circumstance" :-)
while (*pa++ = *pb++) {
cout << ++i << endl;
}
then it will work just fine, outputting:
string a: Good day!
string b: Hi!
1
2
3
string a: Hi!
string b: Hi!
Upvotes: 2