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

时间:2018-05-23 12:34:51

标签: c data-structures

请帮我找一种通过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;

1 个答案:

答案 0 :(得分:0)

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

#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;
}

您可以运行它并检查所有内容是否存储正常。

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