【发布时间】: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