Help recreating strdup()...

Feb 29, 2016 at 4:53pm
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 Feb 29, 2016 at 5:00pm
Feb 29, 2016 at 4:56pm
while (*s) s++; n++;
Is that n++ meant to be part of the while loop?
Feb 29, 2016 at 5:00pm
Yeah, sorry I left out curly braces; results are still gibberish.
Feb 29, 2016 at 5:06pm
return d; d is pointing off the end of the array.
Feb 29, 2016 at 5:10pm
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.