[英]Structure with another structure into it
How can I correctly access the price member from the category structure? 如何从类别结构中正确访问价格成员?
This is the code: 这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SMAX 128
typedef struct {
int price;
char favCharacter[SMAX], edition[SMAX];
} category;
typedef struct {
char title[SMAX], fname[SMAX], lname[SMAX];
category *cat;
} book;
int main(int argc, char **argv) {
book *data = malloc(100 * sizeof(book));
(data->cat)->price = 10; //1
printf("\n\n(*(data->cat)).price is: %d%s", (data->cat)->price, "\n\n");
return 0;
}
My first attempt failed (//1) What is the right way to solve this? 我的第一次尝试失败了(// 1)解决这个问题的正确方法是什么? (I mean to have a structure with another structure) . (我的意思是拥有另一种结构的结构) 。
You are allocating memory for book
, but not for the cat
s inside the books. 你正在为book
分配内存,但不是为book
的cat
分配内存。 Here's an example: 这是一个例子:
/* allocate a hundred books */
book *data = malloc(100 * sizeof *data);
/* allocate one cat per book */
for (i = 0; i < 100; ++i)
data[i].cat = malloc(sizeof *data[i].cat);
/* now you can use it */
for (i = 0; i < 100; ++i)
data[i].cat->price = 50;
Note: you need to add checks to make sure malloc
doesn't fail before continuing using the returned memory. 注意:您需要添加检查以确保malloc
在继续使用返回的内存之前不会失败。 Also, it's best to avoid magic numbers such as 100
above. 此外,最好避免使用上面的100
等魔术数字。 Furthermore, don't forget to free
the memory later. 此外,不要忘记以后free
内存。
You are allocating an array of books in your line: 您正在分配一系列书籍:
book *data = malloc(100 * sizeof(book));
So you should access an array element before accessing its contents: 因此,您应该在访问其内容之前访问数组元素:
data[0].cat->price = 10; // lets access element 0 for example.
But, first, you must also alloc data for the cat
variable inside each array element: 但是,首先,您还必须为每个数组元素中的cat
变量分配数据:
for ( int i = 0; i < 100; i++ ) {
data[i].cat = malloc(sizeof(category));
}
Now you can access your elements correctly. 现在您可以正确访问您的元素。
Don't forget to free the allocated memory. 不要忘记释放分配的内存。
Change 更改
book *data = malloc(100 * sizeof(book));
(data->cat)->price = 10; //1
printf("\n\n(*(data->cat)).price is: %d%s", (data->cat)->price, "\n\n");
to 至
// 1. need explicit conversion
book *data = (book *) malloc(100 * sizeof(book));
// 2. allocate category for book *data
for (int i=0; i<100; i++)
data[i].cat = (category *) malloc(sizeof(category));
// 3. setting
(data[0].cat)->price = 10;
// 4. read
printf("\n\n(*(data->cat)).price is: %d%s", (data[0].cat)->price, "\n\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.