【问题标题】:How to convert a linked list of strings into an array of characters in C?如何将字符串的链表转换为C中的字符数组?
【发布时间】:2017-05-09 22:48:22
【问题描述】:

我有如下链表数据结构:

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;
}

【问题讨论】:

  • 为什么不用char指针来存储每个字符串
  • 很好奇,为什么sizeof(char) * 只是1 *
  • 请注意,您所做的不是字符串数组。它是一个字符数组/一个巨大的字符串。您可能想澄清您的问题。
  • @RaymondChen 是的,string 以空字符结尾。 OP 似乎想要 one 字符串。
  • 你的问题是什么?

标签: c arrays string linked-list


【解决方案1】:

考虑到你已经分配了足够的内存,就这么简单

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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2021-05-09
    相关资源
    最近更新 更多