如何将字符串的链表转换为C中的字符数组?

时间:2016-12-24 16:11:36

标签: c arrays string linked-list

我有以下链表数据结构:

struct _node {
    char *text;
    stuct _node *next;
}

我想编写一个函数,将此链表转换为字符串数组,每个字符串由\ n终止,整个数组以\ 0结尾。

例如,如果链表是:

[first]->[second]->NULL

然后数组应如下所示:

[f][i][r][s][t][\n][s][e][c][o][n][d][\n][\0]

这是我的尝试:

char *convertToArray(struct _node *head){
    assert(head != NULL);

    int lines = findLines(head);
    int i = 0;
    struct _node *curr = head;

    char *textBufferArray = NULL; // return NULL if lines == 0
    textBufferArray = malloc(charCount(head) + lines + 1);
    // malloc enough memory for all characters and \n and \0 characters

    if (lines > 0){
        while (curr->next != NULL){
            strlcpy(textBufferArray[i], curr->text, strlen(curr->text)+1);
            // I need to add a new line here
            curr = curr->next;
            i++;
        }
    }

    I need to add \0 before returning
    textBufferArray[charCount(head) + lines] = '\0';

    return textBufferArray;
}

1 个答案:

答案 0 :(得分:2)

考虑到你已经使用了足够的内存,就像这个

一样简单
int i=0...
while(cur)
{
   int n =strlen(cur->S),k=0;
   while(n--)
     giant[i++]=cur->S[k++];
   giant[i++]='\n';
   cur=cur->next;
}
giant[i++]='\0';