At the beginning of the C file, I define two structures like this.
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
. The void pointer points to a book structure which is also allocated memory in heap.
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. 1 error generated.
I find there's a problem with the expression books.addr[j]
and if I substitute it simply with books.addr
, it will work.
Can somebody instruct me how to fix the problem please?
This is a problem of operator precedence.
Changing book * bk = (book *)books.addr[j];
to book * bk = ((book *)books.addr)[j];
should fix the problem.
error: operand of type 'void' where arithmetic or pointer type is required. 1 error generated.
You are using pointer arithmetic on a void pointer which is not allowed ( addr[ j ] ).
First you have to cast the void pointer
((book *)(books.addr))
And then dereference it
((book *)(books.addr))[j]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.