Another pointer exercise

Hi, i was doing another exercise from my book and it all works but it feels like there must be a better way to do these 2 things :

1. Making this duplicate
2. cout<<'ing pointer what points to an array

Would appreciate if i could learn this the right way with your help!

Exercise :
Write a function char* strdup(const char*), that copies a C - style string
into memory it allocates on the free store. Do not use any standard library functions



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;

char* strdup_2(const char* ch){
	//1. get size
	bool done = false;
	int size = 0;
	while (!done){
		if (ch[size] == '\0')  done = true;
		size++;
	}

	//allocate enough memory and copy each element 
	//from original to duplicate

	char* p = new char[size];
	for (int i = 0; i <= size; i++){
		p[i] = ch[i];
	}
	return p;
}

int main(){
	const char c_str[] = "Hello, world!";
	char* p = strdup_2(c_str);
	
	//print out all chars of duplicate array
	for (int i = 0; p[i] != '\0'; i++){
		cout << p[i];
	}
	system("pause");
}
It looks fine.

Lines 8-11 can be simplified slightly:
1
2
3
 
  while (ch[size])
    size++;


Lines 27-30 can be simplified as:
1
2
 
  cout << p << endl;


cout recognizes const char * as a special case.

I guess cout doesn't count as a standard library function?
1st tnx a lot for answer :) I used cout just to check out if the output is actually correct so i don't think it counts :D

Its interesting how you can cout << p if p is an array but you have to use
cout << *p if p points to a single char. Whats the idea behind this?
Whats the idea behind this?

Compatability with C-style strings.
Thanks for answer :)
Topic archived. No new replies allowed.