strcpy

I'm trying to make a function that copies a string to another string, but my output isn't right. What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

void strcpy2(char*, const char*);

int main() {
	char c[] = "Pizza";
	char d[] = "Apple";

	cout << "Before:" << endl;
	cout << "c: " << c << endl;
	cout << "d: " << d << endl;
	cout << endl;

	strcpy2(d, c);
	cout << "After:" << endl;
	cout << "c: " << c << endl;
	cout << "d: " << d << endl;
	cout << endl;

	return 0;
}

void strcpy2(char *dest, const char *src) {
	while (*src != '\0') {
		*dest = *src;
		src++;
		dest++;
	}
	*dest = '/0';
}


This is what the output looks like:
Before:
c: Pizza
d: Apple

After:
c: Pizza
d: Pizza0╠╠╠╠╠╠╠╠╠╠Pizza
1
2
char c[] = "Pizza";
char d[] = "Apple";


Should be :
1
2
char c[] = "Pizza\0";
char d[] = "Apple\0";


Or :
1
2
char c[] = {'P', 'i', 'z', 'z', 'a', '\0'};
char d[] = {'A', 'p', 'p', 'l', 'e', '\0'};

Last edited on
 
*dest = '\0';


@SakurasouBusters
C-style strings are also known as null terminated strings, so your suggested changes do nothing.
Last edited on
Integralfx is right.

SakurasouBusters, string literals are always null terminated.

char c[] = "Pizza"; is equvalent to char c[] = {'P', 'i', 'z', 'z', 'a', '\0'};.

If you do char c[] = "Pizza\0"; that would mean c is an array of size 7 where the last two elements are null characters.
@cpp1024

have a look at line 31. It's à \ not a /.

Doing so suppresses the null caracter, and provoques an unexpected output depending on what is in memory.

Hope that helps
A compiler does actually warn about the line 31:
31:10: warning: multi-character character constant [-Wmultichar]
 In function 'void strcpy2(char*, const char*)':
31:8: warning: overflow in implicit constant conversion [-Woverflow] 


It does depend on the version of compiler and its options, how verbose they are.
It is a very useful skill to pay attention to what the compiler says.
I see, I used the forward slash by mistake. Thanks for helping!
Topic archived. No new replies allowed.