arrays - 将 char 输入值与数组值进行比较
问题描述
我对编码很陌生。我正在尝试将 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
类型,而是字符数组,所以==
不会像使用 C++ 的 std::string 或 Rust 的 std::string::String 那样工作。
当您使用==
字符数组时实际发生的情况是,数组“衰减”为指针,而 == 运算符实际上只是说“内存位置与casa
”相同的内存位置tabela[j][i]
?
你应该做的是使用标准库函数strcmp
(如果可以,使用strncmp
as usingstrcmp
会导致代码漏洞)。
所以而不是:
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 等在线手册页。
推荐阅读
- c# - 如何发送Linux中断信号?C#
- javascript - 无法替换 html 文本字段
- naming-conventions - 在蛇案例中处理数字的正确方法是什么?
- c# - 如何将 { opencv c++ } 代码集成到使用 c# 以统一 3D 开发的移动应用程序中
- php - 网址中的连字符时清除网址不起作用
- postgresql - 推迟物化视图的创建
- c# - 具有一种属性类型不同的相同类
- javascript - Extjs:由于 Ext.grid.column.Widget 导致网格崩溃
- postgresql - 在postgresql中对jsonb进行排序
- encryption - 一种方式匿名化 - 需要实体加入