September 17th, 2012, 09:37 PM
-
Homework question
Hullo.
I've got to do a homework problem wherein I'm supposed to write a version of strcmp that does not use any C library functions but instead uses pointer notation for the strings it's testing. I'm having some issues here; my facility with PHP and Java is sort of working against me.
Code:
#include <stdio.h>
int stringcomp(char *string1, char *string2);
int main() {
char *string1[5] = "hello";
char *string2[5] = "tests";
int test = stringcomp(&string1, &string2);
if (test == 0) {
printf("same\n");
} else {
printf("not the same\n");
}
return 0;
}
int stringcomp(char *string1, char *string2) {
int counter = 0;
while (*(string1++) != '\0' && *(string2++) != '\0') {
if (string1[counter] > string2[counter]) {
return 1;
} else if (string1[counter] < string2[counter]) {
return -1;
}
counter++;
}
return 0;
}
When I run this code, I get errors on the assignment of the "test" variable -- two "invalid initializer" errors and two "passing argument from incompatible pointer type". I don't need fully written code as an answer but I'd appreciate a hint as to where I'm going wrong here. I tried using (*string1, *string2) as arguments instead, as well as (string1, string2), but the same errors cropped up.
Thanks for any help anyone can provide.
September 18th, 2012, 12:44 AM
-
> char *string1[5] = "hello";
> char *string2[5] = "tests";
Remove the array dimensions, you just have single strings.
> int test = stringcomp(&string1, &string2);
Remove the &
> while (*(string1++) != '\0' && *(string2++) != '\0')
Remove the ++