Reputation: 95
I've written the following program
char *smallest_charachter(char str[]) {
int * min = &str[0];
int size = strlen(str);
for (i=1; i<size; i++)
{
if (str[i]<*min)
{
min = str[i];
}
}
return min;
}
This function is meant to return a pointer to the character with the smallest ASCII value. After doing some testing, my function does not work properly and I can't seem to figure out what the issue is. Any hints or tips to fix my function would help a lot.
Upvotes: 0
Views: 262
Reputation: 33631
No need to use strlen
if we make the for
loop conditional into: str[i]
min
should be char *min
and not int *min
.
You're confusing setup and test and set of min
. In the loop, you set it from the character value when you should set it from the address of the value.
You don't define i
.
Here's some refactored code:
char *
smallest_charachter(char str[])
{
char *min = &str[0];
for (int i = 1; str[i]; ++i) {
if (str[i] < *min)
min = &str[i];
}
return min;
}
Upvotes: 1