Search code examples
cpointerscomparisonc-strings

Compare two strings as in strcmp error error: invalid type argument of unary ‘*’ (have ‘int’)


I am trying to write a C function that compares tho strings not as pointer equality but content equality. But I get an error

error: invalid type argument of unary ‘*’ (have ‘int’)

This is my code:

#include <stdio.h>
#include <stdlib.h>

int stringcompare(char * str1, char * str2, int strSize){
  char * word1 = str1;
  char * word2 = str2;
  
  for (int i = 0; i < strSize; i++) {
    if (*word1[i] != *word2[i]) {
      printf("The strings are DIFFERENT!");
      return 1;
    }
  }
  printf("The strings are a MATCH!");
  return 0;
}

int main(void){
  char * str1 = "Hello World!";
  char * str2 = "Hello World!";
  stringcompare(str1, str2, 13);
}


Solution

  • This if statement

    if (*word1[i] != *word2[i]) {
    

    is incorrect because the expressions word1[i] and word2[i] have the type char. So you may not apply the dereference operator for an object of the type char.

    You should write for example

    if ( word1[i] != word2[i]) {
    

    Pay attention to that the standard string function strcmp has only two parameters and it returns either negative value, or zero or a positive value depending on whether the first string is greater than the second string or is equal to the second string or is less than the second string.

    It seems you mean another standard string function strncmp that indeed has three parameters..

    Also you need to check whether the zero terminating character was already encountered.

    Apart from this the function parameters should have the qualifier const because the passed strings are not being changed within the function.

    The function can be declared and defined the following way

    int stringcompare( const char *s1, const char *s2, size_t n )
    {
        while ( n && *s1 && *s1 == *s2 )
        {
            ++s1;
            ++s2;
            --n;
        }
    
        return n == 0 ? 0 : *s1 - *s2;
    }