implement the strncpy function

I am having trouble implement the string copy function of c++. I think I have the right idea I'm just don't understand why I'm getting errors.

One of my errors is using '\0' and the other is returning *s (it stays it doesn't match the function type but the function is a pointer)

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

using namespace std;

char *mystrncpy(char *s, const char *t, int n)
{

}

	 int strcmp(const char *s, const char *t);
 
		for (; *s == *t; s++, t++) 
		{
			if (*s == ‘\0’) 
				return 0;
		}
			return *s - *t;

int main()
{
   char one[] = "fjiodsjfidjfio";
   char *two =  "rueoiwriouru";
   char *three = "cbn";
   char *four = mystrncpy(one, two, 5);
   cout << one << " " << two << " " << four << " " "\n";
   char *five = mystrncpy(one, three, 5);
   cout << one << " " << three << " " << five << " " "\n";
}

Last edited on
1
2
3
char *mystrncpy(char *s, const char *t, int n)
{
	 int strcmp(const char *s, const char *t);


The bold part is a function declaration. I think you want to call strcmp here, not declare it (even if you want to declare it, it's not allowed at that point).

*s == *t
This is pointless - I really don't know what you're trying to achieve here. But it probably doesn't what you want because it will break the loop if the two strings are different, and cause a segfault if the two are equal.

‘\0’

This should be '\0' not `\0´ - that's a huge difference!

1
2
if (*s == ‘\0’) 
				return 0;


return *s - *t;
Again, pointless. What are you trying to achieve?

Actually, it doesn't look like you're on the right track at all. It rather looks like you completely copy&pasted a strcmp function from somewhere else into your mystrncpy function, and didn't do anything besides that.
Last edited on
Topic archived. No new replies allowed.