Tryingitall987 Tryingitall987 - 2 months ago 5
C Question

strcmp only works at the start of a loop

I've been trying to create a simple program that loops through an array's members and scan the characters looking for a set specific character. I have ran into an issue where

strcmp()
only works at the start of the loop. I'm struggling to understand why this happens and any help would be appreciated.

char *file[3] = {"!x", "!!x", "x!"};

for (int i = 0; i < sizeof(file) / sizeof(file[0]); i++) {
char *line = file[i];
printf("\n");
for (int i = 0; i < strlen(line); i = i + 1) {
char character = line[i];
if (strcmp("!", &character) == 0) {
printf("[YES] %c\n", character);
} else {
printf("[NO] %c\n", character);
}
}
}


Output


[YES] !
[NO] x

[YES] !
[NO] !
[NO] x

[NO] x
[NO] !


Answer

The strcmp function expects the address of a null terminated string. Instead you're passing it the address of a char. strcmp then attempts to read memory locations past character, resulting in undefined behavior.

The real issue however is that you don't want to compare strings. You want to compare characters.

if (character == '!') {
Comments