Home > database >  How do I return a char from a char pointer function in C?
How do I return a char from a char pointer function in C?

Time:03-09

i recently made a function that finds the smallest character in a string. Except when i use assert it does not work. I am not sure how to return the smallest character in a char pointer function.

#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[4] == 'd'));
    printf("Passed\n");
}

CodePudding user response:

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 *.

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.

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;
}

Pay attention to that this asser

assert(smallest(s[4] == 'd'));

is incorrect, It seems you mean

assert( *smallest( s ) == 'd');

CodePudding user response:

There are two problems with your program.

1. Wrong parameters

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'.

2. Wrong return type

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");
}
  • Related