C编程:字符串数组 - 如何检查相等性? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有一个像这样的结构:

struct car{
    char parts[4][10];
};

我在main()函数中初始化它们,好像:

char fill[10] = "none";
struct car c;

int i = 0;
for (i; i< 4; i++){
    memcpy(c.parts[i], fill, 10);
}

此时,数组中的每个字符串都有“none”,如下所示:

int j = 0;
for (j; j<4; j++){
    printf("%s\n", c.parts[j]);
}

*OUTPUT*
none
none
none
none

这是正确的 - 这就是我想要的。但是,现在,我想编写一个函数并将指针传递给c。在函数内部,我想:

  • 检查“parts”数组中的元素是否等于“none”。
  • 如果是,则将其设置为等于“wheel”。

以下是我尝试过的方法:

void fun(struct car* c){
    char fill[10] = "wheel";

    int i = 0;

    for (i; i<4; i++){
          if (c->parts[i] == "none"){
              memcpy(c->parts[i], fill, 10);
          }
    }
}


int main(){ 
    char fill[10] = "none";
    struct car c;

    int i = 0;
    for (i; i< 4; i++){
        memcpy(c.parts[i], fill, 10);
    }

    struct car* c2 = c;
    fun(c2); 

    return 0;
}

但是,函数内部的if语句永远不会被命中!它一直说数组中的每个元素都不等于“无”。但是,我尝试将它打印在if语句之外 - 确实如此,它说“无”!不知道为什么?

编辑我在“可能的重复”帖子(strcmp)中尝试了建议的方法,但无济于事。我仍然没有得到我想要达到的目标。

c arrays string struct memcpy
1个回答
1
投票

使用来自strcmp()<string.h>来比较fun(),如下所示:

void fun(struct car* c){
    char fill[10] = "wheel";

    int i = 0;

    for (i; i<4; i++){
        if (!strcmp(c->parts[i], "none")) {
            memcpy(c->parts[i], fill, 10);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.