Reputation: 31
I have piece of code like this in .c file, which detects, whether the tPerson.name is equal to one of the elements of const char* names[COUNT] or not:
define COUNT 3
...
typedef struct {
int age;
char *name;
} tPerson;
const char* names[COUNT] = {
"xxx", "yyy", "zzz"
};
....
char string[128];
strcpy(string, tPerson.name);//tPerson.name is already initizialed
int counter = 0;
while (counter != COUNT) {
if (strcmp(names[counter], string) == 0) {
counter++;
return 0;
}
}
...
All needed libraries are included. Compiler doesnt detect any errors or warnings, but program isnt working as it should - it does nothing after executing. This piece of code is only a part of the huge program, so I'd like to know, whether this construction is correct and somewhere else in the program is error or not. Thanks
Upvotes: 0
Views: 64
Reputation: 121377
You want to continue the loop if there's no match. Put the statement counter++;
outside the if
statement:
while (counter != COUNT) {
if (strcmp(names[counter], string) == 0) {
return 0;
}
counter++;
}
And use size_t
for counter
instead of int
: size_t counter = 0;
Upvotes: 5
Reputation: 2779
You have return 0
before increasing the counter
if (strcmp(names[counter], string) == 0) {
return 0;
counter++;
}
Upvotes: 1