سؤال

Ok, this must be easy but I'm having one of those days :-p

I have an char* array which for example purposes is as follows:

char* symbols [] = {"++-", "--+"};

I'm trying to loop over symbols[0] and symbols[1] and compare each of the chars to see if its a + or a -

I'm trying:

char* tmp = symbols[0];
for (int i = 0; i < strlen(tmp); i++)
{
    if(strcmp(tmp[i], "+") == 0)
    {
         printf("It's a plus!\n");
    }
    else if (strcmp(tmp[i], "-") == 0)
    {
         printf("Its a minus!\n");
    }
}

However, when compiling I'm getting a warning:

comparison between pointer and integer [enabled by default]

I assume I'm missing something basic - can anyone help me see the wood from the trees?

هل كانت مفيدة؟

المحلول

symbols is of type pointer to char. You need an array of pointers to char.
Change

char* symbols = {"++-", "--+"};  

to

char* symbols[] = {"++-", "--+"};  

and condition in if

if(strcmp(tmp[i], "+") == 0)  

to

if(tmp[i] == '+')

نصائح أخرى

" " and ' ' are not the same. Use single quotes to represent a character, otherwise it's an array of characters (which is an array).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top