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?
If the function returns only a pointer
then it should return a pointer to a string. The local variable length array
retdeclared likeis not built to store a string.
Moreover it will not be alive after exiting the function because it has automatic storage duration. As a result the returned pointer will be invalid and dereferencing it will invoke undefined behavior.
On the other hand, in this return statement
you are returning a string (string literal) that has static storage duration.
You need to allocate memory dynamically for the resulted string in the both cases.
Also this code snippet
is just redundant. Pay attention to that you should use the unsigned integer type
size_tinstead of the signed typeintfor string lengths.And to copy one character array in another character array it is better to use standard C string function
memcpyinstead of using a manually written loop.The function can look for example the following way