I'm supposed to return a 2D array of string words that are common to the input strings.
#include <stdio.h>
#include <malloc.h>
#define SIZE 31
int strcmp1(char *word1, char *word2, int len) {
while (len-- > 0) {
if (!(*word1++ == *word2++))
return -1;
}
return 0;
}
void strcpy1(char *emptyStr, char *str, int len) {
while (len-- > 0) {
*emptyStr++ = *str++;
}
*emptyStr = '\0';
}
void print(char *str) {
for (; *str;)
printf("%c", *str++);
printf("\n");
}
char **commonWords(char *str1, char *str2) {
char *temp1, *temp2;
char commWords[][] = (char**)calloc(10, SIZE);
int i = 0;
if (str1 == NULL || str2 == NULL) {
return NULL;
}
for (temp1 = str1; *temp1; ++temp1) {
if (*temp1 != ' ') {
str1 = temp1;
while (*temp1++ != ' ')
;
int len1 = temp1 - str1;
for (temp2 = str2; *temp2; ++temp2) {
if (*temp2 ! =' ') {
str2 = temp2;
while (*temp2++ != ' ')
;
int len2 = temp2 - str2;
if (len1 == len2) {
if (strcmp1(str1, str2, len1)) {
strcpy1(commWords[i++], str1, len1);
}
}
}
}
}
}
commWords[i] = NULL;
return commWords;
}
int main() {
char *name1 = "abc def ghi";
char *name2 = "ghi abc jkl";
char common[][31] = commonWords(name1, name2);
int i = 0;
while (common[i++] != NULL) {
printf("%s\n", common[i]);
}
}
When I compile this, I get the error: array type has incomplete element type. Since I need to allocate memory within the function, I'm using calloc
to dynamically allocate at most 10 common words of length SIZE
(which is defined as 31). Is there a way to not pre-declare the number of common words (i.e., the first dimension of the array)? And why am I getting this error? Is there a more elegant solution to this problem?