Good afternoon, I use gnu-gcc compiler and it behaves strangely with strings, that is, it simply does not check strings that were assigned via scanf here's the code

 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *command; printf("> "); scanf("%s\n", &command); if (command == "qewr") { printf("programm"); } getch(); return 0; } 

However, it works

 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *command; printf("> "); command = "qewr"; if (command == "qewr") { printf("programm"); } getch(); return 0; } 

    2 answers 2

    Ohhhhhh ...

     char *command; scanf("%s\n", &command); 

    So, you have allocated space for a command variable sized for a pointer (usually, in a 32-bit program, 4 bytes). scanf gets the address of this place, and writes there. If it writes there more than 4 bytes, the output of the array is already getting!

    More - scanf("%s" reads one word - do you need exactly this?

    And then you try to treat this piece of string as a pointer.
    Just awful.

    Why the comparison does not work, you wrote @gbg.

    I would act like this:

     #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> int main() { char command[128]; printf("> "); fgets(command,128,stdin); int lastSymbol = strlen(command)-1; if (command[lastSymbol] == '\n') command[lastSymbol] = 0; if (strcmp(command,"qewr") == 0) { printf("programm\n"); } getch(); return 0; } 
    • Only strlen is better not to count several times. - Qwertiy ♦
    • @Qwertiy I bet that the smart optimizer optimizes this ... but you are right, I will rewrite it. PS Checked. VC ++ 2015 optimized. - Harry
    • A clever optimizer can still replace prints with a putts - bukkojot
    • @bukkojot No, not at all - puts adds \n ... :) - Harry
    • No, sometimes you can. You can look at the dysasms, how compilers and their optimizers work: beginners.re/RE4B-RU.pdf - bukkojot

    Beautifully you put yourself in a funnel - you can not figure it out without 500 ml of a famous drink!

    So, the problem is that you are comparing pointers to strings, and not the contents of these strings.

    In the first case, your pointers are different — the buffer where you wrote scanf and the buffer that the compiler formed.

    In the second case, you are comparing the buffer that the compiler has generated with the buffer that the compiler has generated.

    Next comes the optimizer, which does not allow you to push two identical lines into the program and removes the double. So you are comparing the buffer with yourself.

    Proper string comparison makes strcmp()

    Well, minor problems, like the fact that the memory for scanf must be explicitly allocated.

    • one
      There would still have memory under the buffer ... - Qwertiy ♦
    • And what about the slash? - ishidex2
    • @Duoxx with a slash already I was mistaken - gbg