我正在尝试找出扫描 char* star 值的过程出了什么问题。
struct Property {
unsigned int shift;
int mask;
char * str[4];
}
human [] = {
{0, 1, {"fe", "ma"}},
{1, 1, {"du", "cl"}},
{2, 1, {"nh", "ha"}},
{3, 1, {"sk", "tr"}},
{4, 3, {"bn", "rd", "bw", "bk"}},
{6, 3, {"bu", "ge", "gy", "da"}},
};
int find(char* w){
int i;
int j;
for (i = 0; i < (sizeof(human)/ sizeof(struct Property)); i++){
for (j = 0; j < 4 ; j++){
if (human[i].str[j] == w)
return i;
}
}
}
int main(){
char* w ;
scanf("%s", w);
int k = find(w);
printf("k is %d", k);
return 0;
}
Clion 编译器说“指针参数 w 可以是指向 const 的指针”。所以在我的 main() 中,我尝试使用我的函数扫描 w 作为数组或 char*。
更新建议。
struct Property {
unsigned int shift;
int mask;
char * st[4];
} human [] = {
{0, 1, {"fe", "ma"}},
{1, 1, {"du", "cl"}},
{2, 1, {"nh", "ha"}},
{3, 1, {"sk", "tr"}},
{4, 3, {"bn", "rd", "bw", "bk"}},
{6, 3, {"bu", "ge", "gy", "da"}},
};
int find(char* w)
{
int i;
int j;
for (i = 0; i < (sizeof(human)/ sizeof(struct Property)); i++)
{
for (j = 0; j < 4 ; j++)
{
if ((strcmp(human[i].st[j], w)) == 0)
return i;
else
continue;
}
}
return -1;
}
int main()
{
char* w = malloc(sizeof(char*));
scanf("%99s", w);
int k = find(w);
if (k != -1 )
printf("k is %d", k);
if (k == -1) { printf("%s","Error");}
return 0;
}
仍然没有输出。我真的相信,还是有问题
最佳答案
有几个问题-
分配内存给
w
。否则将未初始化的指针传递给scanf
是未定义的行为。 (你也可以动态分配内存)char w[100]; if( scanf("%99s",w) != 1 ){ /* Handle error */ }
可以使用
strcmp
比较两个字符串。使用==
运算符不是正确的方法。if ( strcmp(human[i].str[j], w) == 0 )
此外,您应该始终从函数中返回一些内容。即使没有匹配项,它也应该返回一些东西。但是你没有遵守那个契约(Contract)。编译器提示。
for(..){ ... } return -1; /* denoting invalid index - search failed*/
您可以轻松地将参数作为
const char *
传递,因为您没有更改它的值(字符串的内容)。
关于c - 在 c 中搜索 char* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117433/