简体   繁体   中英

How to return empty string from a function in C?

How should I return an empty string from a function? I tried using lcp[i] = ' ' but it creates an error. Then I used lcp[i] = 0 and it returned an empty string. However, I do not know if it's right.

Also, is it necessary to use free(lcp) in the caller function? Since I could not free and return at the same time.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 50
char *find_LCP(char str1[], char str2[]);

char *find_LCP(char str1[], char str2[]){

    char * lcp = malloc(MAX_LEN * sizeof(char));

    int a = strlen(str1);
    int b = strlen(str2);
    int min = a < b ? a : b;

    for(int i = 0; i < min; i++){
        if(str1[i] == str2[i])
            lcp[i] = str1[i];
        else
            lcp[i] = 0;
    }

    return lcp;
}

int main()
{
    char str1[MAX_LEN], str2[MAX_LEN];
    char * lcp;

    printf("Enter first word > ");
    scanf("%s", str1);
    printf("Enter second word > ");
    scanf("%s", str2);

    lcp = find_LCP(str1, str2);
    printf("\nLongest common prefix: '%s'\n", lcp);

    free(lcp);
    return 0;
}

An "empty" string is just a string with the first byte zero, so you can write:

s[0] = 0;

However, it is not clear what you are trying to do. The LCP of "foo" and "fob" is "fo" , not the empty string.

You can also return as soon as you find the first non-matching character, no need to go until the end.

Further, you can simply pass the output string as a parameter and have lcp be an array. That way you avoid both malloc and free :

char lcp[MAX_LEN];
...
find_LCP(lcp, str1, str2);

If you want to empty a string without using a for loop then you can do

lcp[0] = 0

but for emptying a string it was right the way you did using a for loop.

There are plenty other ways of emptying the string word by word using for loop:

lcp[i] = '\0';

and it's the right way to make string empty as letter by letter you trying to do using for loop But if you are not using some loops and simply empty a string then you can do this.

memset(buffer,0,strlen(buffer));

but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use:

memset(buffer,0,sizeof(buffer));

Your program has a bug: If you supply two identical strings, lcp[i] = 0; never executes which means that your function will return a string which is not NUL-terminated. This will cause undefined behvaior when you use that string in your printf in main .

The fix for this is easy, NUL-terminate the string after the loop:

int i;
for (i = 0; i < min; i++){
    if(str1[i] == str2[i])
        lcp[i] = str1[i];
    else
        break;
}

lcp[i] = 0;

As for the answer to the question, an empty string is one which has the NUL-terminator right at the start. We've already handled that as we've NUL-terminated the string outside the loop.

Also, is it necessary to use free(lcp) in the caller function?

In this case, it is not required as the allocated memory will get freed when the program exits, but I'd recommend keeping it because it is good practice.


As the comments say, you can use calloc instead of malloc which fills the allocated memory with zeros so you don't have to worry about NUL-terminating.

In the spirit of code golf. No need to calculate string lengths. Pick any string and iterate through it until the current character either null or differs from the corresponding character in the other string. Store the index, then copy appropriate number of bytes.

char *getlcp(const char *s1, const char *s2) {
    int i = 0;

    while (s1[i] == s2[i] && s1[i] != '\0') ++i;

    char *lcp = calloc((i + 1), sizeof(*lcp));
    memcpy(lcp, s1, i);
    return lcp;
}

PS If you don't care about preserving one of input strings then you can simplify the code even further and just return the index (the position of the last character of the common prefix) from the function, then put '\0' at that index into one of the strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM