gpt4 book ai didi

创建字符串链表

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:53 25 4
gpt4 key购买 nike

我不熟悉数据结构和链表。我正在从事名为 Amazon product availability checker using tree in C 的项目。所以我想在树的每个节点中存储字符串,但是在存储字符串时代码没有显示任何错误,但输出也没有被打印出来。我已将节点传递给打印函数来打印字符串,但没有打印任何内容。

我只分享了一个字符串和一个节点的代码。我在 ubuntu 上工作,我正在用 C 语言编码。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
char clothing[10];
struct node *next;
} node;

// 1) creating node

node *create(char const ch[]) {
int i;
node *head = NULL;
node *temp = NULL;
node *p = NULL;
temp = (struct node *)malloc(sizeof(struct node));
temp->clothing[10] = ch[10];
temp->next = NULL;
return temp;
}

// 2) print

void print(node *head) {
node *p = head;
while (p != NULL) {
printf("%s", p->clothing);
p = p->next;
}
}

int main() {
node *head = create("clothing");
print(head);
}

最佳答案

您的create 函数不正确:

  • 您没有测试潜在的 malloc 失败
  • 您没有复制字符串,而只是通过尝试写入超出数组末尾的 clothing[10] 导致未定义的行为。顺便说一下,您阅读的 ch[10] 也可能超出范围。如果 ch 太长,您应该改为复制字符串,同时避免缓冲区溢出。

这是一个改进的版本:

#incude <string.h>
#incude <stdlib.h>

node *create(char const ch[]) {
temp = malloc(sizeof(node));
if (temp != NULL) {
temp->next = NULL;
temp->clothing[0] = '\0';
strncat(temp->clothing, ch, sizeof(temp->clothing) - 1);
}
return temp;
}

从 C99 开始,有一种方法可以分配字符串的副本,而不限制其大小,并且不需要单独分配和 node 结构中的指针。它被称为灵活阵列。这是它的工作原理:

typedef struct node {
struct node *next;
char clothing[];
} node;

node *create(char const ch[]) {
size_t size = strlen(ch) + 1;
temp = malloc(sizeof(node) + size);
if (temp != NULL) {
temp->next = NULL;
memcpy(temp->clothing, ch, size);
}
return temp;
}

关于创建字符串链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55550666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com