views:

125

answers:

7

i am trying to create a function like strlen() in string.h

It's giving me the error can not convert char* to char

#include<stdio.h>
#include<conio.h>

int xstrlen(char string);

void main(void) {
  char string[40];
  puts("Enter string:");
  gets(string);
  printf(" %s is the length of %d", string, xstrlen(string));
}

int xstrlen(char string[]) {
  int i;
  for (i=0; ; i++) {
    if (string[i] == '\0')
      break;
  }// for ends
  return i;
}
+7  A: 

Your prototype:

int xstrlen(char string);

Does not match the function definition:

int xstrlen(char string[]) { ... }

Change the prototype to:

 int xstrlen(char string[]);
bdonlan
Beat me by 13 seconds. :-]
Frerich Raabe
A: 

The xstrlen prototype says that the function takes just a single char. That's what the compiler knows when compiling your main function - and hence it complains, because you're passing an array to it.

Note that the xstrlen definition itself has the correct signature (taking an array).

Just fix the xstrlen prototype to read

int xstrlen(char string[]);
Frerich Raabe
A: 

try:

   int xstrlen(char *string);
Nick
A: 

Your declaration is

int xstrlen(char string);

It should be (as you use later anyway):

int xstrlen(char string[]);

I'd go with char *string instead.

Eiko
A: 
  1. The prototype just before the main is wrong, you wrote

    int xstrlen(char string);
    

    while it should be

    int xstrlen(char string[]);
    
  2. The return type of main is not void, but int.

  3. The next time you'll post a question like this, remember to specify which errors is the compiler giving.
Matteo Italia
A: 

Change int xstrlen(char string); to int xstrlen(char string[]);

you can also improve your function using a while instead of a for loop with a break :

int xstrlen(char string[])
{
  int i;
  i =0;
  while(string[i]!= 0)i++;
  return i;
}
Yassir
A: 

Note the mismatch between this:

int xstrlen(char string);

and this:

int xstrlen(char string[])

They should match (and the latter is the correct one). If you want to get really accurate, it should probably be char const *string, signifying that this function won't modify what's passed to it.

When you're done with that, carry out an exorcism on your code, eliminating its use of gets, then banish that filth from your vocabulary forever, lest ye become an agent of evil! :-)

Jerry Coffin