Home > other >  I am trying to write a function that compares the elements at the same index of 2 character arrays
I am trying to write a function that compares the elements at the same index of 2 character arrays

Time:10-13

I am trying to accomplish this without using any libraries. I have the program comparing the arrays, but it compares all elements to one another. Example of the comparison I am trying to achieve: let's say s1 = "abc" s2 = "xyz" I want the comparison to compare 'a' to 'x' and only 'x' this is what I have so far:

int compare(char *s1, char *s2){
    char *p, *q;
    int x = 0;
    
    for(p = s1; *p != '\0'; p  ){
        for(q = s2; *q != '\0';){
            x = *p - *q;
            if(x < 0){
                x = -1;
                break;
            }
            else if(x > 1){
                x = 1;
                break;
            }
            else
                x = 0;
            return x;
        }
        q  ;
    }}

Things I tried: I tried moving the increment of q outside the for loop, but it did not seem to have an effect. I was also considering using a flag, but could not get it to work.

CodePudding user response:

If you only want to compare the first character you could write it like this:

#include <stdio.h>

int compare(char *s1, char *s2) {
    if(*s1 < *s2) return -1;
    if(*s1 == *s2) return 0;
    return 1;
}

int main() {
    printf("%d\n", compare("a", "b"));
    printf("%d\n", compare("aa", "az"));
    printf("%d\n", compare("b", "a"));
}

and the output is

-1
0
1

The compare function usually takes two void pointers (say, for use in qsort()) in which case you need to cast before dereference or introduce suitable variables.

CodePudding user response:

I am going to assume that you're looking for a comparison of two strings completely, rather than just based on literally the first character in both strings.

A single for loop will suffice for this. As we iterate over both strings using pointer arithmetic, we can check if the character in the first string is less or greater than the corresponding character in the second.

If strings are of differing lengths and control flow in compare "survives" the loop, then we check to see if either pointer is pointing to something other than '\0' (which C among others counts as "false"), and use that to determine which return value to use.

#include <stdio.h>

int compare(char *a, char *b) {
    for (; *a && *b; a  , b  ) {
        if (*a < *b) return -1;
        if (*a > *b) return 1;
    }

    if (*a) return 1;
    if (*b) return -1;

    return 0;
}

int main(void) {
    char *a = "hello";
    char *b = "world";

    printf("%d\n", compare(a, b));

    return 0;
}
  • Related