如何从 category 结构中正确访问 price 成员?
这是代码:
#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;
}
我的第一次尝试失败了 (//1) 解决这个问题的正确方法是什么? (我的意思是有一个结构与另一个结构)。
最佳答案
您正在为 book
分配内存,而不是为书中的 cat
分配内存。这是一个例子:
/* 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;
注意:您需要添加检查以确保 malloc
在继续使用返回的内存之前不会失败。此外,最好避免上面的 100
等魔数(Magic Number)。此外,不要忘记稍后释放
内存。
关于c - 结构与另一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352266/