First of all, your function print_people
has a bug. The line
for (size_t i = 0; people[i].name[0]; ++i)
is wrong. It will read from the array out of bounds, because the loop condition people[i].name[0]
is wrong. This loop condition would only be correct if the array were terminated by an element which has name[0]
set to '\0'
. This was the case in the original version of your question, but not in your current version.
Therefore, you should change the line to the following:
for (size_t i = 0; i < 6; ++i)
In order to count the number of people with a certain name, all you have to do is traverse the array in the same way as you are doing it in the function print_people
and count the number of times you encounter the name you are searching for:
int count_person( const Person *people, const char *target ) {
int count = 0;
for ( int i = 0; i < 6; i++ )
if ( strcmp( people[i].name, target ) == 0 )
count++;
return count;
}
Your entire program would then look like this:
#include <stdio.h>
#include <string.h>
typedef struct Person {
char name[50];
} Person;
void print_people(const Person *people) {
for (size_t i = 0; i < 6; ++i)
printf("%-20s \n", people[i].name);
}
int count_person( const Person *people, const char *target ) {
int count = 0;
for ( int i = 0; i < 6; i++ )
if ( strcmp( people[i].name, target ) == 0 )
count++;
return count;
}
int main() {
Person people[] = { {"Alan"}, {"Bob"}, {"Alan"}, {"Carol"}, {"Bob"}, {"Alan"} };
printf( "Number of occurances of \"Alan\": %d\n", count_person( people, "Alan" ) );
return 0;
}
This program has the following output:
Number of occurances of "Alan": 3
5
solved How can i count a char string in a struct? [closed]