Search code examples
carraysstringstructmemcpy

C Programming: String arrays - how to check equality?


I have a struct such as this:

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

I initialize them in my main() function, as though:

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

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

At this point, each string in the array has "none", like this:

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

*OUTPUT*
none
none
none
none

This is correct - this is what I want. Now, however, I want to write a function and pass a pointer to c. Inside the function, I want to:

  • check if an element in the "parts" array is equal to "none".
  • if it is, then set that equal to "wheel".

Here is how I have attempted this:

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;
}

However, the if statement inside the function never gets hit! It keeps saying that each element in the array IS NOT equal to "none". However, I try printing it out RIGHT ABOVE the if statement - and sure enough, it says "none"! Not sure why?

EDIT I tried the suggested methods in the "possible duplicate" post (strcmp), but to no avail. I'm still not getting what I want to achieve.


Solution

  • Use strcmp() from <string.h> to compare in fun() as shown below:

    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);
            }
        }
    }