我有一个函数,其中
list
是指向链表的指针。这是包含数据节点的链表结构体。typedef struct node{
char *data;
struct node *next;
}NODE;
typedef struct list{
NODE* head;
char *id;
struct list *next;
int size;
}LIST;
我的目标是将列表中的所有数据作为 **char
返回。看起来它工作正常,但在执行 words = (char**) calloc(numOfWords*wordLength,sizeof(char));
这行代码时,我不确定它是否正确,并且它的具体工作原理是什么。您能否检查我的代码并帮助我看出问题所在?谢谢。
char **reset_words(LIST *list){
char ** words;
int i = 0,j = 0,wordLength,numOfWords = list->size;
NODE *p;
for (p = list->head; p != NULL; p = p->next) {
wordLength = my_strlen(p->data);
words = (char**) calloc(numOfWords*wordLength,sizeof(char));
for(int k=0;k < wordLength;k++){
words[i][j] = p->data[k];
j++;
}
i++;
}
return words;
}
malloc
(或calloc
、realloc
)的返回值进行强制类型转换,这是不必要的。参见:Do I cast the result of malloc? - David C. Rankin