我想弄清楚扫描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 )
for(..){
...
}
return -1; /* denoting invalid index - search failed*/
const char *
传递,因为您没有更改它的值(字符串的内容)。