开发者

Compare a specific array element to a string with "if" in C?

开发者 https://www.devze.com 2022-12-23 06:58 出处:网络
Rather Trivial Question. So I tried to do this: if (array[0]==\"some_string\") where array is a list of strings

Rather Trivial Question.

So I tried to do this:

if (array[0]=="some_string")

where array is a list of strings

array[0] = "some_string_1";
array[1] = "some_string_2";
array[2] = "some_string_3";

but obviously it doesn't work..开发者_Go百科. What do I have to do?


if(array[0] == 'n')

"" signifies string
'' signifies char

Note: 'a' is a char and "a" is a string, so 'a' != "a"

char is a single character (actually int), so if you want to compare strings, use strcmp instead.


in the example you give, you are comparing a single character (array[0]) with the address of a compiled-in string ("some_string").

Because a string literal is treated as a null-terminated character array, and comparisons against a character array with the == operator compare the address of the array.

The example you gave is essentially similar to this:

char* x = "some_string";
char array[10];
if(array[0] == x)
    ...

And you can see from this example that the types simply don't match. As another poster stated, you use the [] operator to obtain a specific character from the offset in the brackets from the start of the array.

0

精彩评论

暂无评论...
验证码 换一张
取 消