0

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.

user545642
  • 91
  • 1
  • 14
  • Dear Govind, I tried the methods in that post and it still did not work (strcmp). – user545642 Feb 13 '19 at 00:34
  • if you're working with strings, you should use string functions (`strcpy`, `strcmp`, etc). If you're working with arbitrary data, then use the likes of `memcpy`, `memcmp`, etc ... although `memcpy` and `memcmp` should work perfectly well with strings also. – yano Feb 13 '19 at 00:41
  • 2
    `if (c->parts[i] == "none"){` needs to be changed to something like `if (strcmp(c->parts[i], "none") == 0){`. In what you have, the operator `==` is comparing the value of 2 pointers, where `c->parts[i]` is in memory, and where `"none"` is in memory. These are not equal, so the condition fails. `==` does not compare the content of the strings. – yano Feb 13 '19 at 00:44

1 Answers1

1

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);
        }
    }
}
programmer
  • 411
  • 4
  • 10