Here's my attempt to loop through an array of strings.
I created an array of ids, compared each id to a voterID which is being read from the console.
// helper function
int verifyVoterID(char *uidDB[], char *voterID)
{
for (int i = 0; i < sizeof(uidDB[0]); i++)
{
if (uidDB[0][i] == voterID)
return 0;
}
return 1;
}
int main()
{
char *uidDB[] = {"001", "002", "003"}, *voterID;
printf("\n\nEnter ID: ");
scanf("%s", voterID);
// Verify voter's ID
if (voterID)
verifyVoterID(uidDB, voterID) == 0
? doSomthing()
: doSomethingElse();
return 0;
}
OUTPUT:
./03.c: In function 'verifyVoterID':
./03.c:19:21: warning: comparison between pointer and integer
19 | if (uidDB[0][i] == voterID)
|
I've also tried using strcmp() to compare
int verifyVoterID(char *uidDB[], char *voterID)
{
for (int i = 0; i < sizeof(uidDB[0]); i++)
{
if (strcmp(uidDB[0][i], voterID) == 0)
return 0;
}
return 1;
}
OUTPUT:
./03.c: In function 'verifyVoterID':
./03.c:19:24: warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast [-Wint-conversion]
19 | if (strcmp(uidDB[0][i], voterID) == 0)
| ~~~~~~~~^~~
| |
| char
What am I missing ?
strcmp(uidDB[i], voterID). Also, you need to pass in the size of the array.sizeof(uidB[0])gives the size of achar *which is not what is wanted.sizeof(uidDB[0])and(sizeof(uidDB) / sizeof(uidDB[0])). I get4,3respectively. But using the second instance in the helper function I get another error:./03.c: In function 'verifyVoterID': ./03.c:16:30: warning: 'sizeof' on array function parameter uidDB' will return size of 'char **' [-Wsizeof-array-argumen ] 16 | for (int i = 0; i < (sizeof(uidDB) / sizeof(uidDB[0])); i++) | ^ ./03.c:13:25: note: declared here 13 | int verifyVoterID(char *uidDB[], char *voterID) | ~~~~~~^~~~~~~