我正在做这个家庭作业,它要求我接受一个巨大的字符串,并将其分成许多子字符串,其中每个字符串由字符串内的“\n”新行值指示,并将其存储到一个链表,例如:
string = "hello world\n i need help!!"
会变成:
string1 = "hello world\n"
string2 = "i need help!!"
我已经编写了这段代码,它将字符串分解为子字符串并将它们存储到单独的节点中。代码本身非常丑陋,需要更多的改进,但我什至无法达到这一点,因为中间似乎发生了一些奇怪的事情,链接列表中的所有字符串都被我添加到的最后一个字符串替换链表...
这是我的代码,如果可以的话请帮忙:
#define eq(A, B) ( A == B )
typedef struct list * link;
typedef char Item;
struct list {
link next;
Item *string;
};
void printlist (link ls);
link newLS (char text[]);
link newNode (char text[]);
void insertNode (link next, Item item[]);
link newLS (char text[]) {
int i = 0;
int j = 0;
char temp[(strlen(text))];
link new = NULL;
while (text[i] != '\0') {
temp[j] = text[i];
if (text[i] == '\n' || text[i+1] == '\0') {
temp[j+1] = '\0';
j = -1;
if (new == NULL) {
new = newNode(temp);
printf("new: %s", new->string);
} else {
insertNode(new, temp);
printf("new: %s", new->next->string);
}
}
i++;
j++;
}
printlist(new);
return new;
}
link newNode (char text[]) {
link new = malloc(sizeof(*new));
assert(new != NULL);
new->string = malloc ((strlen(text)) * sizeof(char));
new->string = text;
new->next = NULL;
return new;
}
void insertNode (link ls, Item item[]) {
assert (ls != NULL);
assert (item != NULL);
while (ls->next != NULL) {
ls = ls->next;
}
ls->next = newNode(item);
}
int main(int argc, char **argv) {
link ls;
ls = newLS("1\n2\n3");
return 0;
}
我们必须使用这个函数:
link newLS (char text[])
最佳答案
#define eq(A, B) ( A == B )
不是一个好主意,改进的方法是将其定义为#define eq(A, B)((A)==(B))
您分配缓冲区,然后不使用它,而是将另一个指针分配给该指针:
new->string = malloc ((strlen(text)) * sizeof(char)); new->string = text;
相反,您应该从给定的指针复制数据:
new->string = malloc ((strlen(text) + 1) * sizeof(char)); memcpy(new->string, text, strlen(text) + 1);
此外,当您尝试
释放
分配的内存时,您会遇到段错误,因为new->string
没有指向分配的区域。 .
关于c - 我的链接列表有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5567056/