首页 > 解决方案 > 如何将结构存储在链表中

问题描述

所以我正在处理这个问题,我必须将一个结构放入一个链表中,但我无法让它正常工作。这意味着当我尝试通过列表从结构中打印某些数据时,我只是得到一个地址或其他东西。这是我的代码示例。任何小提示将不胜感激。感谢您的时间!PS我不知道如何在这里为我的代码添加颜色。如果你也能告诉我,我将不胜感激<3

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



typedef enum {red, green, blue, yellow, cyan, magenta, black} Color;

typedef struct rect{
    int id;
    int x;
    int y;
    int w;
    int h;
    int area;
    Color colour;
    int filled;
}rec;

/*Linked list node */
typedef struct Node{
    rec data;
    struct Node *next;
}N;

N *head;
N *tail;

void add_list(N *p)
{
    N *new_node;
    new_node = (N*)malloc (sizeof(N));
    if (new_node == NULL)
    {
        printf("ERROR!");
        exit(EXIT_FAILURE);
    }
    *new_node = *p;
    new_node->next = head;
    head = new_node;

}

void show_list()
{
    N *p;
    
    p=head;
    while(p != NULL)
    {
        printf("%d\n", p->data.x);//lets say i want to print data.x
        p = p->next;
    }
}


void free_stack(void){
    N *p, *next_node;

    p = head;
    while(p != NULL)
    {
        next_node = p->next;
        free(p);
        p = next_node;
    }
}

int main(){
    int n, max_w, max_height, i, col;
    rec *obj;
    N s;
    char tmp[8];
    head = NULL;
    FILE* fp;
    fp = fopen("input.txt", "r");
    //simple example of stdout
    //fprintf(stdout, "HELLO");
    fscanf(fp, "%d %d %d", &n, &max_w, &max_height);
    obj = (struct rect *)malloc(n * sizeof(struct rect));//allocating memory for all the shapes
    if(obj == NULL){
        printf("ERROR!");
    }
    for(i = 0; i < n; ++i){
        fscanf(fp,"%d %d %d %d %s %d\n", &(obj + i)->x, &(obj + i)->y, &(obj + i)->w, &(obj + i)->h, tmp, &(obj + i)->filled);
        if((((obj + i)->x) < 0 || ((obj + i)->x) > max_w) || (((obj + i)->y) < 0 || ((obj + i)->y) > max_height)){
            printf("rectangle %d has wrong definition", i);
            return -1;           
        }
        if(strcmp(tmp, "red") == 0){
            
            (obj + i)->colour = red;
        }else if(strcmp(tmp, "green") == 0){
            
            (obj + i)->colour = green;
        }else if(strcmp(tmp, "blue") == 0){
            
            (obj + i)->colour = blue;
        }else if(strcmp(tmp, "yellow") == 0){
            
            (obj + i)->colour = yellow;
        }else if(strcmp(tmp, "cyan") == 0){
            
            (obj + i)->colour = cyan;
        }else if(strcmp(tmp, "magenta") == 0){
            
            (obj + i)->colour = magenta;
        }else if(strcmp(tmp, "black") == 0){
            
            (obj + i)->colour = black;
        }
    }
    
    for(i = 0; i < n; ++i){
        //printf("%d\t%d\t%d\t%d\t%d\t%d\n", (obj + i)->x, (obj + i)->y, (obj + i)->w, (obj + i)->h, (obj + i)->colour, (obj + i)->filled);
        (obj + i)->id = i;//id of each rect
        (obj + i)->area = ((obj + i)->w * (obj + i)->h);//area of each rect
        add_list(&s);
        

    }
    show_list();

    
    free_stack();
}

标签: c

解决方案


推荐阅读