Your code has four issues.
- You use
gets
to catch the string from stdin
. Never ever use gets
. It is deprecated because of security reasons since with that, you could easily run into buffer overflow, when the input string is longer than the buffer itself. gets
don´t stop scanning.
Why is the gets function so dangerous that it should not be used?
Use fgets
instead, which limits the input according to the size of the buffer:
fgets(str, sizeof str, stdin);
- Wrong parameter type of
distinct_or_not_string()
:
char distinct_or_not_string(char *string []);
string
is of type char **
but you want to pass a pointer to a string. Use either char string[]
or char *string
where string
is of type char *
.
- The second while loop uses the the wrong object to proof the condition,
i
instead of j
:
while(string[i]!='\0')
- Use of
printf
as return value of distinct_or_not_string()
:
return printf("false");
printf()
will be always evaluated to 1
(assuming no error has occurred at printing) and thus result
in the main
function would always have 1
regardless of the string has any character twice or more or not, which is not appropriate.
Split both and make each statement separate:
printf("false");
return 0;
and
printf("true");
return 1;
Side note:
distinct_or_not_string()
does not need to return a char
; the return value in this case has nothing to do with a string or a character of it.
So the return type of distinct_or_not_string()
shall, in my opinion, preferable be int
for better readability and to avoid confusions, although it isn´t a syntactic mistake to use char
instead. The declaration of the function would then be like that:
int distinct_or_not_string(char *string);
The corrected code should be like that:
#include <stdio.h>
int distinct_or_not_string(char* string);
int main()
{
char str[20];
int result;
printf("please enter your string: ");
char *p = fgets(str,sizeof str,stdin);
if(p == NULL)
{
printf("Error occurred at reading the input!");
return 1;
}
printf("\n");
result = distinct_or_not_string(str);
return 0;
}
int distinct_or_not_string(char *string)
{
int i=0,j;
while(string[i] != '\0')
{
j=i+1;
while(string[j] != '\0')
{
if(string[i] == string[j])
{
printf("false");
return 0;
}
j++;
}
i++;
}
printf("true");
return 1;
If you want to test this code online, here is the link: https://onlinegdb.com/H1PCstoSL