Check while statement string comparison conditions

Asked 1 years ago, Updated 1 years ago, 162 views

int main(void)
{

    char* str[7] = { "tiger", "applemango", "pear", "anteater", "strawberry", "eagle", "end" };

    char* st = malloc(sizeof(char)*4);

    while (*st != "end")
    {
        printf ("Search word (end) : ");
        scanf("%s", st);

        for (int i = 0; i < 7; i++)
        {
            if (strcmp(str[i], st) == 0)
            {
                printf("%d" has the same word!\n", i+1);
                break;
            }
        }
        printf("\n");       
    }
    free(st);
    return 0;
}

I wrote *st!="end" as the condition of the while statement, but even if I initialize *st to end, it does not escape.

If you set while(1) and set break; under the if statement *st!="end" condition, it will escape, but I'm not sure.

pointer while-loop if-else c

2022-09-21 11:35

1 Answers

In C, you cannot simply compare strings in the same way that == or !=. C++ may be different, but comparisons between character arrays cannot be done. Because that equation is not looking at the contents of the two, but comparing the stored addresses.

Also, this is a side note, but it seems that you are receiving input from st, but the memory capacity received by st is too small. Some of the strings shown in the str array are much larger than this, which may not work as intended. Even if possible, it can cause problems with the memory of other programs.

So,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char* str[7] = { "tiger", "applemango", "pear", "anteater", "strawberry", "eagle", "end" };

    char* st = (char*) calloc(255, sizeof(char));

    while (strcmp(st, "end"))
    {
        printf ("Search word (end) : ");
        scanf("%s", st);

        for (int i = 0; i < 7; i++)
        {
            if (strcmp(str[i], st) == 0)
            {
                printf("%d" has the same word!\n", i + 1);
                break;
            }
        }
        printf("\n");
    }
    free(st);
    return 0;
}

Please understand that there are parts that I arbitrarily adjusted.

First of all, as I said before, if the string is the same, we use strcmp in C. If the return value of strcmp is 0, it will be the same, so it will exit after receiving the end. However, if this is the case, even if 'end' is entered, the printf will operate once more and exit. This is an algorithmic problem.

*st means the first letter of the st string when viewed as a character, and even in this way, the comparison target is a string called "end", so it is impossible to compare.


2022-09-21 11:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.