0

I am comparing data stored in a 2D array that I read from a file to a character array with data in it. It looks like this:

char file[10][20];
file[0] = "test";
char arry[20] = "test";
if (arry == file[0]) {
    //do something
}
else {
    // do something else
}

The issue is that the //do something statement is not being executed, I have made sure there are no new line characters that were left on when the file was read into the array. Thanks for any help

  • Possible duplicate of [Comparing two strings in C?](https://stackoverflow.com/questions/14232990/comparing-two-strings-in-c) – Raviprakash Feb 10 '18 at 16:35

1 Answers1

1

Don't be misquided by the similar syntax of file[0] = "test"; and char arry[20]="test";

First is assigning a decayed pointer to the string literal to a char[20] object which is type mismatch error.

Second is declaration of char array with initialization of the content with that of the string literal. This is different from the one shown above.

You can do a quick strcpy(file[0],"text") which would work. But then again use strcmp and friends to compare these two strings.

if(strcmp(file[0],arry) == 0){
   ...
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
  • strcmp may have problem when meet 0 in data, so better to use memcmp? – How Chen Feb 11 '18 at 02:50
  • @HowChen.: That's why we use strcmp to compare string, what's the use of `memcmp` here? We specifically want to compare the charcaters until we met `\0`...it doesn't matter to compare what is beyond the `\0`. – user2736738 Feb 11 '18 at 03:17
  • ok, I think maybe the data file may contain 0, for example I always do similar thing to real from binary file and compare to some patterns – How Chen Feb 11 '18 at 03:20
  • @HowChen.: That's a different context. In your case purpoe is not to compare string rather to compare the content of binary file or so on... – user2736738 Feb 11 '18 at 03:21