我应该返回输入字符串共有的字符串单词的二维数组。
#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]);
}
}
当我编译它时,出现错误:数组类型具有不完整的元素类型。由于我需要在函数内分配内存,因此我使用 calloc
动态分配最多 10 个长度为 SIZE
(定义为 31)的常用词。有没有办法不预先声明常用词的数量(即数组的第一维)?为什么我会收到此错误?这个问题有更优雅的解决方案吗?
最佳答案
你用错了。
首先,如果你想拥有二维动态数组样式,请使用指向指针的指针。 记住,这不是二维数组!
char ** commWords;
然后为指针分配内存:
//Allocate memory for 10 pointers to char
commWords = malloc(sizeof(*commWords) * 10);
然后,对于每个单词,分配单独的内存
//Allocate memory for each element for string
for (int i = 0; i < 10; i++) {
commWords[i] = malloc(sizeof(*commWords[i]) * SIZE); //Allocate memory with length of SIZE
}
然后按预期使用分配的内存。
关于c - 错误 : array type has incomplete element type; dynamic 2D array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569516/