c - 如何将结构存储在链表中
问题描述
所以我正在处理这个问题,我必须将一个结构放入一个链表中,但我无法让它正常工作。这意味着当我尝试通过列表从结构中打印某些数据时,我只是得到一个地址或其他东西。这是我的代码示例。任何小提示将不胜感激。感谢您的时间!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();
}
解决方案
推荐阅读
- python-3.x - 如何从 dictionary.values() Python 中获取最常见的单词或按字母顺序排列的情况
- vb.net - 如何检查一个字符串是否包含来自其他字符串的所有字符(以任何顺序)?
- java - 如何在Java中根据条件创建子列表
- python - 有没有办法让 instagram bot 检测器
- angular - Angular displays only ID number from Java REST
- excel - 由命名参数评估的 Vba 函数
- javascript - 如何设置 Vue 路由或覆盖后退按钮以像应用程序一样运行
- python - Web Scraping - 我需要登录 LinkedIn 才能进行 webscrape (scrapy)
- mongodb - MongoDb:以原子方式存储聚合和域事件
- regex - 用于捕获带有新行的模式的正则表达式