10

I have the following:

int findPar(char* str)
{
int counter=0;

while (*str) 
{
    if(str[0] == "(") <---- Warning
    {
        counter++;
    }
    else if (str[0]== ")") <---- Warning
    {
        counter--;
    }
    if (counter<0) 
    {
        return 0;
    }
    str++;
}

if (counter!=0) 
{
    return 0;
}
return 1;
}

The warning i get is comparison between an int and a char.

I tried to do the comparison (first char in the string vs. given char) also with strcmp like this:

    if (strcmp(str, ")")==0) { stuff }

but it never goes in to 'stuff' even when the comparison (should) be correct.

how should i do it?

Itzik984
  • 15,968
  • 28
  • 69
  • 107
  • 1
    Use single quotes. `")" == )\0` literally, whereas `')' == )`. – chris May 07 '12 at 23:46
  • `strcmp( str, ')' ) ==0)` does not work because your are comparing the whole string char* against a single literal character. It would work if you did `strcmp( str[0], ')') == 0` I think – EdChum May 07 '12 at 23:47
  • @EdChum `strcmp` expects it parameters to be string. ')', a char of value `41` will be converted to `(char*)41`. So the function will look into the memory address `41`, hoping to see a string and instead - BAM! Segfault. – Imp May 07 '12 at 23:57
  • @Imp OK, I wasn't sure which was why I annotated my guess with think, thanks for pointing that out – EdChum May 08 '12 at 00:04

4 Answers4

21

If str is a C string (null-terminated array of chars), then str[0] is a char.

Note that the type of quotes matters! ')' is a char, while ")" is a string (i.e. a ')' char followed by a null terminator).

So, you may compare two chars:

str[0] == ')'

or you may compare two strings

strcmp(str, ")") == 0

naturally, (the second works if str string really only contains that parenthesis).

Imp
  • 8,409
  • 1
  • 25
  • 36
7

You're comparing a character (str[0]) with a const char[N] ("whatever"). You need to use single quotes because double quotes denote character arrays, whereas single quotes denote single characters:

if (str[0] == ')') // or *str == ')'

Etc.

The reason why strcmp was failing as well was because, while the string at some time does point to the ), it has more characters beyond that (i.e. is not followed immediately by a '\0') so the string is not equivalent to the string ")" which has one character.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
2

Double quotes, " are string delimiters, so ")" is a pointer to a string literal in if(str[0] == "("). You want to compare to a character, so you have to use single quotes

if(str[0] == '(')
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

You need if (str[0] == ')') etc. Note the single quotation marks (apostrophes) to denote character literals.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084