Try using strlen but get error: Conflicting types for 'strlen'

1.2k views Asked by At

I can't figure out what causes this problem... appreciate any help! I've tried a lot of codes for strlen but this one was the only one that I could implement with only 1 error. With this code, I'm trying to read a string from a file, break it in words separated by space, determinate the length and then print the word and the length to the user.

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

FILE*arquivo;
char nuks[80];
char frase[80];

typedef struct node {
char palavra;
struct node* esquerda;
struct node* direita;
int altura;
} No;

size_t strlen(char *nstr)
{
int total=0;
char str[80];
strcpy(str, nstr);
total = strlen(str);
printf("|%s| is |%d|", str, total);
}

int main()
{
No* raiz = NULL;
arquivo=fopen("README.txt","r");
fgets(nuks, 79, arquivo);
printf("%s\n",nuks);

char *parte;

// Get the first word
parte = (char*)strtok(nuks, " ");

// Get the other words
while(parte != NULL){
strlen(parte);
printf("%s\n", parte);
parte = (char*)strtok(NULL, " ");
}

printf("\n\n");
system("pause");
return 0;
}
4

There are 4 answers

0
Horacio On

You are calling a function named strlen() into a function also named strlen(), which makes it recursive and, what is worse, infinitely recursive! Besides that, you don't need to have a local copy of nstr into str just for determining its length. Finally, is there any reason for not using the standard strlen() function declared in string.h?

0
Andreas DM On

size_t strlen(const char *) is already defined in <string.h>, therefore the conflict.
You should choose another function name for your function.

0
Sagar Kar On

1> The standard strlen is conflicting with local strlen. (Probably the conflict error is here )

2> The fuction is not properly coded, calling recursively itself without any exit point.

The first one can be ignored as local definition will overload the one in string.h But the problem is in the function.

0
Arial On

Note that in your code, you've included the C string library

#include <string.h>

which has the function

size_t strlen(const char *str) 

that returns the length of the string passed into the function.

However, in your code, you try to overwrite the function

size_t strlen(char *nstr)

which causes confusion when C tries to compile your file. Try to use a different name for your function instead. For example:

/* This function prints the length of string */
void print_strlen(char *nstr) {
    int total=0;
    total = strlen(nstr);
    printf("|%s| is |%d|", nstr, total);
}

Also, note that in your code, you defined

 char str[80];

which then copies the input nstr to str.

This is ok so long as the length of the string doesn't exceed 79 (note that there is a null terminator '\0' for string). But as soon as the length of your string exceed that limit, your output will be a bit funny!