#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    4
    Rep Power
    0

    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.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,381
    Rep Power
    1871
    > 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 ++
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo