0
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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have tried that, it does not work either, and I get a warning "main.c:63:30: warning: comparison between pointer and integer"
@asdqq Please not the single quotes, '#' and enable compilation warnings. You either 1. Didn't try that! 2. Your input does not have a # as the first character.
Ah, thank you, that and using '#' instead of "#" solved my problem. The issue was with the '&', i didn't notice you changed that as well, my bad!
1

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

line[0] == '#'

Comments

1
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.

3 Comments

'#' is probably the intent, not "#".
I have tried that, it does not work either, and I get a warning "main.c:63:30: warning: comparison between pointer and integer"
Thank you @DeiDei , that and not using "&" solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.