[英]Compare char input value with array values
我對編碼很陌生。 我正在嘗試將 char 輸入值與數組值進行比較,但似乎我的代碼根本沒有(正確地)比較它。
我到目前為止的代碼是:
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;
}
因為 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]
”?
您應該做的是使用標准庫 function strcmp
(如果可以,請使用strncmp
,因為使用strcmp
會導致代碼漏洞)。
所以而不是:
if (casa == tabela[j][i]) { /* CODE*/ }
做:
if (strcmp(casa, tabela[j][i]) == 0) { /* CODE*/ }
甚至更好:
if (strncmp(casa, tabela[j][i], 80) == 0) { /* CODE*/ }
您可以通過搜索“foo 手冊頁”(其中 foo 顯然替換為 strncmp 或類似的東西)在線找到 strncmp/strcmp 等在線手冊頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.