力扣,这样写为啥输出是Null,怎样改才会有输出?

img

力扣的,这样写为啥输出是Null,怎样改才会有输出?返回一个数组不行吗?

代码被我稍微修改了一下,具体看注释。仅供参考,谢谢!

明显的问题就是:首先这个a数组要声明为静态,不然是返回不了的!static char a[200];这样

img

img

#include<stdio.h>
#include<string.h>

//strsn是字串个数
char *longestcommonPrefix(char **strs ,int strsn);


int main()
{
    char *str[3]={"bower","elow","flight"};
    char *p=longestcommonPrefix(str,3);
    printf("%s\n",p);
    return 0;
}

char *longestcommonPrefix(char **strs ,int strsn)
{
    static char a[200];
    //因为字串长短不同,n值不能随便取,只能取最短那个。
    //不然可能会导致数据溢出
    int len;
    int n = strlen(strs[0]);
    for(int i=1;i<strsn;i++)
    {
        if((len=strlen(strs[i]))<n)
        {
            n=len;
        }        
        
    }
    
    int x = 1, y = 0;
    for (int j = 0; j < n; j++)
    {
        for (int g = 1; g < strsn; g++)
        {
            if (strs[0][j] != strs[g][j])
            {
                x = 0;
                break;
            }
        }
        if (x == 1)
        {
            a[y] = strs[0][j];
            y++;
        }
        else break;
    }
    
    //不管存不存在共同前缀最后都要添加字符串结束符,这是好习惯。
    a[y]='\0';
    
    if (y != 0)
        return a;
    //strsSize = 2;
    return "";
}