'How can I search an element in an array with strcmp
Animal is a struct and name is one of its attribute. What I want is when I write a name in scanf, it should iterate in the array uing strcmp and when it returns 0 then it should print that index in the array.
void SearchAnimalName(Animal *animalName, uint8_t number_of_animals)
{
char search[10];
scanf("%s", search);
for (int i = 0; i < number_of_animals; i++)
{
if (strcmp(search, (animalName + i)->name) == 0)
{
return animalName->name;
}
}
}
Solution 1:[1]
Your function has the return type void.
void SearchAnimalName(Animal *animalName, uint8_t number_of_animals)
That is it returns nothing and the compiler should issue a message for this return statement
return animalName->name;
Also it is unclear why the second parameter has the type uint8_t and at the same time you are using a variable of the type int within the for loop.
.
for (int i = 0; i < number_of_animals; i++)
If you want to return the index then the function should be declared like
size_t SearchAnimalName( const Animal *animalName, size_t number_of_animals)
{
char search[10];
scanf("%9s", search);
size-t i = 0;
while ( i < number_of_animals && strcmp(search, animalName[i].name) != 0 )
{
i++;
}
return i;
}
The function returns the index of the found element or the array size in case when the target element is not found.
To output the index you need to use the conversion specifier zu as for example
size_t i = SearchAnimalName( animalName, number_of_animals );
if ( i != number_of_animals ) printf( "i = %zu\n", i );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad from Moscow |
