#include <stdio.h>
#include <string.h>
char* longestConsec(char* strarr[], int n, int k)
{
char* longest_arr[k];
unsigned int longest_len = 0;
if (n == 0 || k > n || k <= 0)
return "";
for (int i = 0; i < (n - (k - 1)); i++)
{
/*
if(( strlen(strarr[i]) + strlen(strarr[i + 1]) ) > longest_len)
{
longest_len = strlen(strarr[i]) + strlen(strarr[i + 1]);
memmove(longest_arr1, strarr[i], 10);
memmove(longest_arr2, strarr[i + 1], 10);
}
*/
unsigned int cmp_len = 0;
// get the length of every k consecutive string in a list and add them up to cmp_len
for (int j = 0; j < k; j++)
cmp_len += strlen( strarr[i + j] );
// compare if cmp_len is greater than longest_len then add that string into longest_arr overlap the previous one
if (cmp_len > longest_len)
{
for (int m = 0; m < k; m++)
memmove(longest_arr[m], strarr[i + m], strlen(strarr[i + m]) + 1); // the first suspect
longest_len = cmp_len;
}
}
// if there is more than 1 consecutive string then the output is combine of k consecutive string in the list
if (k > 1)
{
for (int l = k - 1; l >= 0; l--)
strcat(longest_arr[l - 1], longest_arr[l]); // the second suspect
}
// return the longest_arr[0] the string that have been combine
return longest_arr[0];
}
int main(void)
{
// test subject
char* a1[] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
char* newstring = longestConsec(a1, 8, 2);
printf("%s\n", newstring);
return 0;
}
when i try to run it got Segmentation fault. I suspect it is the memcpy and strcpy function but don't know how to fix it. The code is suppose to do get in a list of string and then check k consecutive string in that list, and print out the concatenation of those string.