Strncmp

Hello,

having trouble implementing a strncmp function. Full description is here:

http://www.cplusplus.com/reference/cstring/strncmp/


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
35
36
37
38
39
40
41
42
43
44

#include <stdio.h>
#include <string.h>

#undef strncmp


int strncmp(const char *s, const char *t, size_t num)


  	
{
	
	 for ( ; num >0;  s++, t++, num--)
		 
	 
	        if (*s != *t)
	          return *s - *t;
		  
		 
            else if (*s == 0)
			  return 0;
	      
}
	  
 



 int main ()
 {
   char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
   int n;
   puts ("Looking for R2 astromech droids...");
   for (n=0 ; n<3 ; n++)
     if (strncmp (str[n],"R2xx",2) == 0)
     {
       printf ("found %s\n",str[n]);
     }
   return 0;
 }


 



Why this isn't compiling?
Why this isn't compiling?
Post compiler error here. There are no psychics here and we cannot know what happened.

In this case it is simple. There are already strncmp function declared in C standard library, so there cannot be another one. Choose different name for it.
put a break point at for loop line , you should see then if the program goes within the for loop scope. Note that you method does not have a default return value , for instance put at least return -1;
Ericool wrote:
put a break point at for loop line , you should see then if the program goes within the for loop scope
Sure, it would help with non-compiling code.
What do you mean?

Here is the error message:
warning: control may reach end of non-void function
[-Wreturn-type]
}
Technically that's not an error. It's just saying that it is possible that your function which says it will return an int, might not (n might be 0), in which case nothing would happen.
Here is my current code:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

#include <stdio.h>
#include <string.h>




int mystrncmp(const char *s, const char *t, size_t num)


  	
{
	
	 for ( ; num >0;  s++, t++, num--)
		 
	 {
		 
	 
	        if (*s != *t) 
	          return *s - *t;
		  
		     
		 
            else if (*s == 0) 
			  return 0;
	       
		   
	 }
	 
	 return 0;
}
	  
 



 int main ()
 {
   char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
   int n;
   puts ("Looking for R2 astromech droids...");
   for (n=0 ; n<3 ; n++)
     if (mystrncmp (str[n],"R2xx",2) == 0)
     {
       printf ("found %s\n",str[n]);
     }
   return 0;
 }



Output:
Looking for R2 astromech droids...
found R2D2
found R2A6
Topic archived. No new replies allowed.