2

Edit: This is a duplicate and I've flagged it as such. See [question] Why is "a" != "a" in C?

So I'm trying to print out a specific message depending on a field within a struct. The field contains the string "1".

Whenever I run printf("%s", record.fields[2]); the output is 1; I've no format warnings.

However, when I check the field against the corresponding string (in this case, "1"), it fails the check:

if (record.fields[2] == "1") {
    printf("The field is 1!");
}
Community
  • 1
  • 1
Piper
  • 1,266
  • 3
  • 15
  • 26

1 Answers1

2

You need to use strncmp to compare strings:

if (strncmp(record.fields[2], "1", 1) == 0) ...

You need to compare to zero, because strcmp returns zero when two strings are identical.

However, it looks like you are not comparing strings: rather, you are looking for a specific character inside the string. In this case, you need to use a character constant instead of a string literal (with single quotes):

if (record.fields[2] == '1') ...
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    In case record.fields is a `char*`, OP should be using the character '1' as the comparison target – hd1 Apr 20 '13 at 02:53
  • @hd1 You're right, strncmp is better. Edited. Thanks! – Sergey Kalinichenko Apr 20 '13 at 02:56
  • 1
    @PolyShell Please take a look at the edit. – Sergey Kalinichenko Apr 20 '13 at 03:03
  • Again, @PolyShell, what does the declaration of record.fields look like? – hd1 Apr 20 '13 at 03:07
  • @dasblinkenlight Thanks for the edit, that was the issue and I'm good to go and on my way. I can always count on Stack Overflow to help me through a tough spot! – Piper Apr 20 '13 at 03:10
  • 2
    As long as one of the arguments is guaranteed to have a `NULL` terminator (as is the case here with `"1"`), I see no reason to use `strncmp` rather than `strcmp`. – Joshua Green Apr 20 '13 at 04:43
  • @Joshua Green Should the field `.field` be <= size than the `strlen("123")`, and `.field` is not `'\0'` terminated, then `strncmp(record.fields[2], "123", sizeof record.fields[2])` has an advantage over `strcmp(record.fields[2], "123")` as it prevents comparing past the size of `record.fields[2]`. Of course, with `"1"`, the point is moot. – chux - Reinstate Monica Jul 13 '15 at 19:04