Search code examples
cpointersc-stringsstring-comparisonfunction-definition

Which string is the longest


My code: What I'm trying to do is to input two strings, then return the longest one. If they're the same length then return NULL. Now, the code is just outputting gibberish and I cannot find out why. The function returns a pointer to the first character of the largest string. Then it goes through the while loop, and I'm trying to dereference the pointer and print out its value.

Note: I'm revising for an exam and we have to use only pointers and not treat strings as arrays.

#include<stdio.h>

char* string_ln(char*, char*);
 
int main() {
    char str1[20];
    char str2[20];
    char* length;
   
    scanf("%s%s", str1, str2);
   
    length = string_ln(str1, str2);
   
    while (length != '\0') {
        printf("%c", *length);
        length++;
    }
}
 
char* string_ln(char*p1, char*p2) {
    int count1 = 0;
    while (*p1 != '\0') {
        count1++;
        p1++;
    }
   
    int count2 = 0;
    while (*p2 != '\0') {
        count2++;
        p2++;
    }
   
    if (count1 > count2) {
        return p1;
    }
    else if (count2 > count1) {
        return p2;
    }
    else {
        return NULL;
    }
}

Solution

  • There are a few problems here. First, you're modifying p1 and p2 in the function, so you won't actually return a pointer to the beginning of the largest string, but to its end. One way to avoid this is to iterate over copies of p1 and p2:

    char* string_ln(char*p1, char*p2)
    {
       char* tmp1 = p1;
       int count1 = 0;
       while (*tmp1 != '\0') {
          count1++;
          tmp1++;
       }
       
       char* tmp2 = p2;
       int count2 = 0;
       while (*tmp2 != '\0') {
          count2++;
          tmp2++;
       }
       
       if(count1>count2){
           return p1;
       }
       else if(count2>count1){
           return p2;
       }
       else{
           return NULL;
       }
    }
    

    Second, in your main, you're using the %c format string, which works for a single char, not a whole string. Since you have a string anyway, you can avoid a format string and just print it directly. Also, note that you should explicitly check for NULLs:

    int main() {
       char str1[20];
       char str2[20];
       char* longest;
       
       scanf("%s%s", str1, str2);
       
       longest = string_ln(str1, str2);
       
       if (longest) {
           printf(longest);
       } else {
           printf("They are the same length");
       }
    }