[英]A pointer “addr” in a struct was allocated memory but when I call it in another function, it can't work
At the beginning of the C file, I define two structures like this. 在C文件的开头,我定义了两个这样的结构。
typedef struct
{
char name[LEN];
double price;
} book;
typedef struct
{
void *addr;
int num;
} Array;
Array book;
Later, I use malloc(sizeof(void *)*len)
to allocate memory to the pointer addr
. 稍后,我使用
malloc(sizeof(void *)*len)
将内存分配给指针addr
。 The void pointer points to a book structure which is also allocated memory in heap. void指针指向一个书结构,该书结构也在堆中分配了内存。
After doing this, when I call it in another function in this way: 完成此操作后,当我以这种方式在另一个函数中调用它时:
void print_view_of_books(Array books)
{
int j;
int limit = books.num;
for(j=0; j<limit; j++)
{
book * bk = (book *)books.addr[j];
printf("Book title: %s\n", bk->name);
printf("Book price: %lf\n", bk->price);
puts("----------------------");
}
}
My compiler says 我的编译器说
error: operand of type 'void' where arithmetic or pointer type is required.
错误:类型为“ void”的操作数,其中需要算术或指针类型。 1 error generated.
产生1个错误。
I find there's a problem with the expression books.addr[j]
and if I substitute it simply with books.addr
, it will work. 我发现表达式
books.addr[j]
存在问题,如果我将它简单地替换为books.addr
,它将起作用。
Can somebody instruct me how to fix the problem please? 有人可以指导我如何解决问题吗?
This is a problem of operator precedence. 这是运算符优先级的问题。
Changing book * bk = (book *)books.addr[j];
更改
book * bk = (book *)books.addr[j];
to book * bk = ((book *)books.addr)[j];
book * bk = ((book *)books.addr)[j];
should fix the problem. 应该解决问题。
error: operand of type 'void' where arithmetic or pointer type is required.
错误:类型为“ void”的操作数,其中需要算术或指针类型。 1 error generated.
产生1个错误。
You are using pointer arithmetic on a void pointer which is not allowed ( addr[ j ] ). 您正在不允许的void指针(addr [j])上使用指针算术。
First you have to cast the void pointer 首先,您必须强制转换void指针
((book *)(books.addr))
And then dereference it 然后取消引用
((book *)(books.addr))[j]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.