asd qq
asd qq

Reputation: 53

Comparing char in string with pointer in C

char * line = NULL;
size_t len = 0;
FILE *fp = fopen("test.rpn", "r");
while ((read = getline(&line, &len, fp)) != -1) {
    if(&line[0] == "#"){
            exit(0);
    }
}

This doesn't work, the first character of a line is # and yet it is not exiting. I have also tried 0/1/2/3/4 just to see if it was so weird start of line issue but it is not.

Upvotes: 0

Views: 63

Answers (3)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Instead do this

if (line[0] == '#') // Note the single quotes

When you take the address surely the comparison is false regardless of what character is at line[0] because you are comparing addresses1 and you can be certain that they will be different. You instead need to compare the values.

Also, when you see a warning it usually means that something is wrong. If you see a warning and yet nothing is wrong then you surely were expecting such warning. If the warning is unexpected, you did something bad.


1&line[0] is the same as line so you are comparing the address of line which is a pointer to the address of the string literal "#" which with all certainty is not the same.

Upvotes: 4

David Ranieri
David Ranieri

Reputation: 41017

if(&line[0] == "#"){

should be

if(line[0] == '#'){

You want to compare the first character of the string and line is already a string, there is no need to take the address of (&), also use single quotes instead of double quotes.

Upvotes: 1

omri_saadon
omri_saadon

Reputation: 10621

&line means the address of the line, you want his value and therefore use :

line[0] == '#'

Upvotes: 1

Related Questions