String exercise

Hello,

I need to write a function char* strdup(const char* p) that copies a c-style string into memery it allocates on the free store.

I`m not sure how to start solving this...

Here is what I have so far:

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
33
#include <iostream>

char* strdup(const char* p)

{

  int n = 0;
  while (p[n]) ++n;

  for(char& p : n) {
  
  char* a = new char [n+1];
  a[i] = p[i];
 
  }
  
  delete[] a;

  return n;

  
}


int main()

{

   char word[] = "Hello";

   strdup(word);

}
Last edited on
http://linux.die.net/man/3/strdup

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
33
34
#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

char *strdup(const char *s);

int main()
{
	char source[] = "Hello";
	char *destination = NULL;
	
	destination = strdup(source);
	
	cout<<destination<<endl;
	
        delete[] destination;
	return 0;
}

char *strdup(const char* source)
{
	//length of source
	int len = strlen(source);	
	
	//allocate memory enough for copy
	char *dest = new char[len];
	
	for(int i = 0; i < len; i++)
		dest[i] = source[i];
	
	return dest;
}
Last edited on
Topic archived. No new replies allowed.