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
#include <iostream>
usingnamespace std;
char* strdup_2(constchar* 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 = newchar[size];
for (int i = 0; i <= size; i++){
p[i] = ch[i];
}
return p;
}
int main(){
constchar 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");
}