gpt4 book ai didi

c - 如何从c中自定义类型的节点列表中读取数据结构

转载 作者:行者123 更新时间:2023-11-30 16:31:38 27 4
gpt4 key购买 nike

请帮我找到一种方法,用 C 语言读取/添加一些内容到这个数据列表中。我对 typeDef 语句感到困惑。

typedef struct price
{
unsigned dollars;
unsigned cents;
} Price;

/**
* Stores data for a stock item.
**/
typedef struct stock
{
char id[ID_LEN + NULL_SPACE];
char name[NAME_LEN + NULL_SPACE];
char desc[DESC_LEN + NULL_SPACE];
Price price;
unsigned onHand;
} Stock;

/**
* The node that holds the data about an item stored in memory.
**/
typedef struct node
{
Stock *data;
struct node *next;
} Node;

/**
* The list of products - each link in the list is a Node.
**/

typedef struct list
{
Node *head;
unsigned size;
} List;

最佳答案

为了正确写入内存,需要正确分配后者。我在这里给你留下一个例子(我省略了所有检查,但这些应该完成!):

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

#define N 5
#define ID_LEN 64
#define NAME_LEN 64
#define DESC_LEN 64

typedef struct price
{
unsigned dollars;
unsigned cents;
} Price;

/**
* Stores data for a stock item.
**/
typedef struct stock
{
char id[ID_LEN];
char name[NAME_LEN];
char desc[DESC_LEN];
Price price;
unsigned onHand;
} Stock;

/**
* The node that holds the data about an item stored in memory.
**/
typedef struct node
{
Stock *data;
struct node *next;
} Node;

/**
* The list of products - each link in the list is a Node.
**/

typedef struct list
{
Node *head;
unsigned size;
} List;

int main() {
List l;
int i;
l.size = N;
l.head = (Node*) malloc (l.size * sizeof(Node));
for (i = 0; i < l.size; i++) {
l.head[i].data = (Stock*) malloc (sizeof(Stock));
}

//you can now fill you data
//example
strcpy(l.head[0].data->id, "test\n");
printf("id of element 0: %s\n", l.head[0].data->id);
//example
strcpy(l.head[1].data->name, "Paul\n");
printf("name of element 1: %s\n", l.head[1].data->name);
//example
l.head[2].data->price.dollars = 99;
l.head[2].data->price.cents = 99;
printf("price of element 2: %d.%d $\n", l.head[2].data->price.dollars, l.head[2].data->price.cents);

return 0;
}

您可以运行它并检查一切是否都存储正常。

注意:接下来我没有连接节点指针!

关于c - 如何从c中自定义类型的节点列表中读取数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488578/

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