Help recreating strdup()...

Rules:
No standard library functions may be used.
No subscripting is allowed.

Here's what I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char* strdupl(const char* s)
{
	//find length of s
	int n = 0;
	while (*s){ s++; n++; }
	s -= n;

	//create new C-style string
	char* d = new char[n];

	//deep copy old string into new string
	for (int i = 0; i < n; ++i) {
		*d = *s;
		d++; s++;
	}

	return d;
}


However, the results are gibberish and I don't know what I've done wrong.
Last edited on
while (*s) s++; n++;
Is that n++ meant to be part of the while loop?
Yeah, sorry I left out curly braces; results are still gibberish.
return d; d is pointing off the end of the array.
Yes it was! I'm pretty new to pointer arithmetic so I'm very sloppy about it. Thank you very much for the help!
Topic archived. No new replies allowed.