-1

I am just trying to learn C and trying to understand the structs and the pointers. One of the programs I wrote is getting compiler error as below:

:29:18: error: request for member 'price' in something not a structure or union.

Sample program :

#include <stdio.h>
#include <stdlib.h>

typedef struct  {
    char *Title;
    float price;
} Book;


int main()
{
    int a  = 10;
    Book *HFJ = malloc(sizeof *HFJ)  ;
    HFJ->Title = "Head First Java";
    HFJ->price = 200;
    void *object;
    object = &a;
    printf("Value of object is %d", * (int*)object);
    printf("Value of HFJ %f", HFJ->price);
    object = HFJ;
    (Book*)object->price = 300;
    return 0;
}
compor
  • 2,239
  • 1
  • 19
  • 29
  • 1
    Add some [C reference](https://en.cppreference.com/w/c) website to your bookmarks, and look quite often into it; both for the C language, and for the functions of the [C standard library](https://en.wikipedia.org/wiki/C_standard_library) (e.g. `malloc`; `printf` etc...). Later, refer also to the C11 standard [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) when in doubt – Basile Starynkevitch Aug 23 '18 at 09:08

2 Answers2

5

I guess the line you're getting the error on is this one

(Book*)object->price = 300;

The error is because of operator precedence, where the "arrow" operator -> have higher precedence than the cast operator.

That means your statement is really like this:

(Book*)(object->price) = 300;

That means you're try to dereference the void * variable object (which is not really possible) and then cast the price member to Book *.

To correct it use

((Book*)object)->price = 300;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
4
(Book*)object->price = 300; 

is equivalent to

((Book*)(object->price)) = 300;

You want

((Book*)object)->price = 300;
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34