I have this function where list is a pointer to a linked list. This is the list struct which contains nodes with data.
typedef struct node{
char *data;
struct node *next;
}NODE;
typedef struct list{
NODE* head;
char *id;
struct list *next;
int size;
}LIST;
My goal is to take every data from the list and return it as a **char. It looks like it works but the line where i do words = (char**) calloc(numOfWords*wordLength,sizeof(char)); I'm not sure if it's correct and how it works exactly. Can you see anything that is going wrong in my code and help me? Thanks.
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;
}
After i looked at your code here are some changes:
wordLength = strlen(list->head->data). strcpy(words[i],p->data) to add the string to your words array.Try this out let me know if it works.
char **reset_words(LIST *list){
char ** words;
int i = 0,j = 0,wordLength = strlen(list->head->data),numOfWords = list->size;
NODE *p;
words = (char **)malloc(numOfWords * sizeof(char *));
for (int h=0; h<numOfWords; h++)
words[h] = (char *)calloc(wordLength,sizeof(char));
for (p = list->head; p != NULL; p = p->next) {
strcpy(words[i],p->data);
i++;
}
return words;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With