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);
}
CodePudding user response:
For an array, pointed to by *ptr
, an element at position i
is dereferenced by *(ptr i)
, which is the equivalent of ptr[i]
and not *ptr[i]
.
CodePudding user response:
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 subscript 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 || *s1 - *s2;
}