I have an array of strings as follows:

char *sCmdInt[8];

I am filling this array by tokenizing a line of text from a file. I then want to check if element 0 of the array is equal to a value.
Eg:

if (sCmdInt[0] == "ReadMemory32")
	{
		// do stuff
	}

When debugging, I can see that the values are equal, but it doesn't evaluate to true for some reason; it just skips to the next statement.
I tried using strcmp also:

if (strcmp(sCmdInt[0], "ReadMemory32"))
	{
		// do stuff
	}

but this causes an access violation as sometimes there won't be anything in sCmdInt[0].
I have tried first checking if sCmdInt[0] is null also

if (sCmdInt[0] == NULL)

// also

if (sCmdInt[0] > 0)

// also

if (&sCmdInt[0] == "")

// and other combinations

but this didn't work either.
I tried storing the two variables as pointers and then using strcmp but still getting an access violation.
Somebody please help!!

Recommended Answers

All 6 Replies

You were on the right track using strcmp in your second example. But you said that it wasn't returning true.

Strcmp returns '0' when two strings are equal (which equates to false). It's a classic gotcha. So your second example should read:

if (strcmp(sCmdInt[0], "ReadMemory32") == 0)
	{
		// do stuff
	}

I hope this helps.

I did try this also, but I am still getting an access violation every time I try to use strcmp.

if (sCmdInt[0] == "ReadMemory32")

wasn't returning true. Sometimes, the array won't contain values, which is why I think the access violation is occurring.

When you declare sCmdInt, are you declaring it within a function or in static space?

If you're declaring it within a function, you need to set all of the elements to NULL *before* running any code. Otherwise, it'll be filled with garbage.

myfunction()
{
    char *sCmdInt[8];
    int i;
    
    for ( i = 0; i < 8; i++ )
        sCmdInt[i] = NULL;

    /* Do stuff */

    if ( sCmdInt[0] != NULL )
    {
        if ( strcmp(sCmdInt[0], "ReadMemory32") == 0 )
        {
            /* Do more stuff */
        }
    }
}

Maybe that's what's going on, and why your NULL checks aren't working. If that's not the case, post the entire function.

commented: Quick responses, thanks for the help! +1

Thank you, this works!

how do i solve this porg...
to read a standard input and print the number of occurences of characters in graphic mode...??

Maybe you should start a new thread with this. A suggestion for a solution is to have a while loop with a counter:

while (cin != '\r') // while the user doesn't hit return
count++;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.