Reputation:
i recently made a function that finds the smallest character in a string. I am not sure how to return the smallest character in a char pointer function.
#include <stdio.h>
#include <string.h>
char * smallest(char s[])
{
char small = 'z';
int i = 0;
while (s[i] != '\0')
{
if (s[i] < small)
{
small = s[i];
}
i++;
}
return small;
}
int main(void)
{
char s[4] = "dog";
printf("%c",smallest(s));
}
Upvotes: 0
Views: 974
Reputation: 310990
The variable small
has the type char
according to its declaration
char small = 'z';
//...
return small;
and this variable is returned from the function while the function return type is the pointer type char *
.
char * smallest(char s[])
Also if the user will pass an empty string to the function then you will try to return the character 'z'
as a smallest character though this character is absent in the empty string.
I think in this case you should return a pointer to the terminating zero character '\0'
.
The function can be defined the following way
char * smallest( char s[] )
{
char *small = s;
if ( *s )
{
while ( *++s )
{
if ( *s < *small ) small = s;
}
}
return small;
}
Or as in C there is no function overloading then the function should be declared and defined like
char * smallest( const char s[] )
{
const char *small = s;
if ( *s )
{
while ( *++s )
{
if ( *s < *small ) small = s;
}
}
return ( char * )small;
}
Pay attention to that this assert
assert(smallest(s[4] == 'd'));
is incorrect, It seems you mean
assert( *smallest( s ) == 'd');
Or after you updated your program you need to write
printf("%c\n",*smallest(s));
instead of
printf("%c",smallest(s));
Using this function you can not only to find the smallest character but also to determine its position in the source string.
For example
char *small = smallest( s );
printf( "The smallest character is '%c' at the position %tu\n",
*small, small - s );
or
char *small = smallest( s );
if ( *small == '\0' )
{
puts( "The source string is empty" );
}
else
{
printf( "The smallest character is '%c' at the position %tu\n",
*small, small - s );
}
Upvotes: 2
Reputation: 9188
There are two problems with your program.
The function smallest(char[] s)
expects to be given an character array but what you are passing in as an argument is s[4] == 'd'
which is not a character array.
This has nothing to do with the assert()
itself.
What you want to do is assert(smallest(s) == 'd')
.
Your function is declares that it would return *char
(= a pointer to a char) but you are trying to return a char
. So you should adjust the return type of your function to be char
.
The correct program:
#include <stdio.h>
#include <assert.h>
#include <string.h>
char smallest(char s[]) {
char small = 'z';
int i = 0;
while(s[i] != '\0') {
if (s[i] < small) {
small = s[i];
}
i++;
}
return small;
}
int main(void) {
char s[4] = "dog";
assert(smallest(s) == 'd');
printf("Passed\n");
}
Upvotes: 0