创建字符串的链接列表 [英] Creating linked list of strings
问题描述
我是数据结构和链表的新手.我正在使用C中的树进行名为 Amazon产品可用性检查器"的项目.因此,我想将字符串存储在树的每个节点中,但是在存储字符串时,代码未显示任何错误,但输出也未得到打印.我已经通过节点打印功能来打印字符串,但是没有打印任何内容.
I am new to data structures as well as to linked lists. I am working on project named as Amazon product availability checker using tree in C. So I want to store strings in each node of the tree but while storing strings the code is not showing any error but the output is also not getting printed. I have pass the node to print function to print the string but nothing is getting printed.
我只共享了一个字符串和一个节点的代码.我正在研究ubuntu,并且正在使用C语言进行编码.
I have shared the code for one string and one node only. I am working on ubuntu and I am coding in the C language.
这是我的代码:
#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
太长,则应避免缓冲区溢出.
- you do not test for potential
malloc
failure - you do not copy the string, but merely cause undefined behavior by attempting to write to
clothing[10]
which is beyond the end of the array. By the way, you readch[10]
which may well be out of bounds too. You should instead copy the string, while avoiding a buffer overflow ifch
is too long.
这是一个改进的版本:
#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
结构中进行单独的分配和使用指针.它称为灵活数组.运作方式如下:
Since C99, there is a way to allocate a copy of the string without a limitation on its size, and without the need for a separate allocation and a pointer in the node
structure. It is called a flexible array. Here is how it works:
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;
}
这篇关于创建字符串的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!