views:

184

answers:

3

Rather Trivial Question.

So I tried to do this:

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

but obviously it doesn't work... What do I have to do?

+4  A: 
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.

N 1.1
" " actually signifies char*, but you're still right otherwise.
Matthew Iselin
..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 Jacinto
@San: i cant explain everything in detail here :)
N 1.1
A: 

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.

San Jacinto
A: 

What was the solution to this problem? I have a similar problem, except I am actually comparing a string. I have an array of strings with around 8 elements. I want to check the first element for equality with a string. Eg.

if (array[0] == "ReadMemory") // do stuff

strcmp doesn't work for me here as sometimes there won't be a value in array[0]. I've tried to first check array[0] for a null value, but that doesn't work either. Any suggestions?

ftl25
`strncpm(array+pos, "ReadMemory", 9)`
R..
that doesn't work, it's still throwing an access violation. As i said sometimes array[0] won't have a value. So trying to access it using strcmp or strncmp doesn't work. Any other suggestions?
ftl25