So I am solving the "Longest Common Prefix" problem on Leetcode in C and have almost got it working. My Code:
char * longestCommonPrefix(char ** strs, int strsSize){
int minlen = strlen(strs[0]);
for(int i=0; i<strsSize; i++){
int len = strlen(strs[i]);
if(len<minlen){
minlen=len;
}
}
int len=0;
for(int i=0; i<minlen; i++){
int match=1;
char check = strs[0][i];
for(int j=0; j<strsSize; j++){
if(strs[j][i]!=check){
match=0;
break;
}
}
if(match==0){
break;
}
else{
len++;
}
}
if(len==0){
return "";
}
char ret[len];
for(int i=0; i<len; i++){
ret[i] = strs[0][i];
}
for(int i=0; i<len; i++){
printf("%c",ret[i]);
}
return ret;
}
Printing out the array ret is working out and is giving expected output. But when I am returning the char array ret, it is returning (null). So the array is storing the value correctly, but there is some issue with returning it. Can someone please help with this?
retgoes out of scope whenlongestCommonPrefix()returns. It effectively doesn’t exist anymore. Either pass a pointer to the buffer in to populate it or dynamically allocate it.retis not NUL terminated.return(“”);in one case and a pointer to a dynamically allocated buffer in another. The calling function should free memory if allocated bylongestCommonPrefix()but it doesn’t know if the pointer returned points to allocated memory or a string literal (unless it “knows” a zero-length string is a literal). Best not to mix and match; Vlad’s answer avoids the problem.