Why can’t I use || for pointer?

Asked

Viewed 117 times

3

I have the following code:

int i=0;
variable a;
a.type = CHAR;
a.name = malloc(sizeof(char)+1);
while(*l->str++ != ' ');
while(*l->str != ';' || *l->str != '='){
    a.name = realloc(a.name, ((!i)?1:i)*sizeof(char)+1);
    a.name[i] = *l->str;
    i++;
    *l->str++;
}
a.name[i] = '\0';
printf("%s\n", a.name);

But he gives segment fault.

When I withdraw the *l->str != '=' or the *l->str != ';' of the condition of while it works normally. I wonder why it gives segment fault and if there is any way without if to solve.

  • What is l->str? Where is the statement of this?

  • It’s been a while since I’ve programmed in C, what’s the precedence of the operators || and !=? Could the compiler be interpreting this as *l->str != (';' || *l->str) != '='?

  • 1

    I don’t think so, I’m pretty sure that’s not the problem.

  • 3

    The condition *l->str != ';' || *l->str != '=' will always be true. The only way she can be false is if *l->str for ; and = at the same time. Obviously, this will never happen. The same variable cannot have two different values.

  • @Havenard I believe you are right about precedence. The problem is right in the condition.

1 answer

7


Seems to me your problem is that while no exit condition: it will continue forever! (or better, it will continue until you give a segfault) Suppose your string is simply:

;=

Using while(*l->str != ';') what happens?

  1. Is different from ;? No. So step out of the loop.

Already using while(*l->str != '='):

  1. Is different from =? Yeah. Go to the next
  2. Is different from =? No. So step out of the loop.

But using while(*l->str != ';' || *l->str != '='):

  1. Is different from ;? No, but it’s different than =? Yeah. Go to the next
  2. Is different from ;? Yeah. Go to the next
  3. Segmentation fault

That is, the problem is in your condition. See if what you really want is not a &&.

  • Man, thanks, I traveled with this ||.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.