0

How to find a string in a 2D array of char in C

Given the two dimensional array of characters in C: char arr[5][3]={"11","22","33","44","55"}; how do you find the index of "22" in the given array? This loop doesn't seem to work: int i = 0; char ch[3] = "22"; while(i < 5){ if(arr[i] == ch){printf("Index of \"22\" = %d",i); break;} i++; }

29th Mar 2020, 9:49 AM
H2727
H2727 - avatar
2 RĂ©ponses
+ 1
You cannot use == to compare 2 strings in C. That basically compares their addresses since a string is a char array. In <string.h>, there is strcmp(char*, char*), Which compares 2 strings and return 0 if they are equivalent. In a nutshell, include <string.h> and use !strcmp(arr[i], ch).
29th Mar 2020, 10:01 AM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
0
Thanks!
29th Mar 2020, 10:07 AM
H2727
H2727 - avatar