0

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... What do I have to do?

0

2 Answers 2

9
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.

Sign up to request clarification or add additional context in comments.

3 Comments

" " actually signifies char*, but you're still right otherwise.
..But you can only use strcmp() if the string is null-terminated, or if you know the array size of both strings to exceed a length n-1, you can us strncmp().
@San: i cant explain everything in detail here :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.