Tryingitall987
Tryingitall987

Reputation: 355

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] !

Upvotes: 0

Views: 1347

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

The problem here is, you're supplying wrong argument to strcmp(), the &character is not a pointer to a string.

Quoting C11, chapter int strcmp(const char *s1, const char *s2);

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

So, it expects both the arguments to be of string type, which in your case is not.

You can simply use the comparison operator == to compare chars, like

 if (line[i] == '!')  //notice the '' s, they are not ""s

and so on.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753990

strcmp() compares null terminated strings. In the code:

char character = line[i];
if (strcmp("!", &character) == 0) 

the character is not a null-terminated string. It is accidental that it works at all.

You need something more like this to compare strings:

char character[2] = { line[i], '\0' };
if (strcmp("!", character) == 0) 

Or like this to compare characters:

char character = line[i];
if (character == '!') 

Upvotes: 0

dbush
dbush

Reputation: 223972

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 == '!') {

Upvotes: 2

Related Questions