Как читать структуру данных из списка узлов с пользовательскими типами в C - PullRequest
0 голосов
/ 23 мая 2018

Пожалуйста, помогите мне найти способ прочитать / добавить что-то в этот список данных на языке Си.Я запутался в 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 голосов
/ 23 мая 2018

Для правильной записи в память необходимо правильно выделить последнюю.Я оставляю вам пример (я пропустил все проверки, но они должны быть выполнены!):

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

Вы можете запустить его и проверить, что все хранится нормально.

ПРИМЕЧАНИЕ:Я не подключил указатель узла дальше!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...