简体   繁体   English

将 char 输入值与数组值进行比较

[英]Compare char input value with array values

I'm fairly new to coding.我对编码很陌生。 I am trying to compare char input value with array values, but it seems my code isn't comparing it (correctly) at all.我正在尝试将 char 输入值与数组值进行比较,但似乎我的代码根本没有(正确地)比较它。

The code I have so far is:我到目前为止的代码是:

int main() {
    int colunas = 5;
    int linhas = 6;
    char casa[80];
    char tabela[80][6][5] = {{"a5", "b5", "c5", "d5", "e5", "f5"},
                                      {"a4", "b4", "c4", "d4", "e4", "f4"},
                                      {"a3", "b3", "c3", "d3", "e3", "f3"},
                                      {"a2", "b2", "c2", "d2", "e2", "f2"},
                                      {"a1", "b1", "c1", "d1", "e1", "f1"}};
    scanf("%s", casa); 
      
    for (int i = 0;i< colunas; i++) {
        for (int j = 0;j < linhas; j++) {
            printf("%s",tabela[i][j]);

            // Problem happens here.
            if (casa == tabela[j][i]) {
                printf("Verdade");
            }
        }
        
        printf("\n"); 
    }
    printf("%s", casa);

    return 0;
}

Because C doesn't really have a string type, but instead a arrays of characters, the == will not work like it would with C++'s std::string or Rust's std::string::String.因为 C 并没有真正的string类型,而是一个 arrays 字符,所以==不会像使用 C++ 的 std::string 或 Rust 的 std::string::String 那样工作。
Whats actually happening when you use == with arrays of characters, is that the arrays "decay" into pointers, and the == operator is actually just saying "is the memory location of casa the same memory location as tabela[j][i] "? Whats actually happening when you use == with arrays of characters, is that the arrays "decay" into pointers, and the == operator is actually just saying "is the memory location of casa the same memory location as tabela[j][i] ”?
What you should do is use the standard library function strcmp (if you can, use strncmp as using strcmp can result in code vulnerabilities).您应该做的是使用标准库 function strcmp (如果可以,请使用strncmp ,因为使用strcmp会导致代码漏洞)。
So instead of:所以而不是:

if (casa == tabela[j][i]) { /* CODE*/ }

do:做:

if (strcmp(casa, tabela[j][i]) == 0) { /* CODE*/ }

or even better:甚至更好:

if (strncmp(casa, tabela[j][i], 80) == 0) { /* CODE*/ }

You can find the man pages online for strncmp/strcmp and such online by just searching "foo man page" (where foo is obviously replaced with strncmp or something like that).您可以通过搜索“foo 手册页”(其中 foo 显然替换为 strncmp 或类似的东西)在线找到 strncmp/strcmp 等在线手册页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM