Pointers to structs

Hi. I have some logic trouble (again) regarding the assignment of struct data type variables. E.g. 1: declaring a normal variable (var) of struct data type

1
2
3
4
5
6
7
8
  //program in c
#include <stdio>
#include <stdlib.h>
struct a
{int x,y;} var;
int main(void)
{var=9;
return 0;}

This error shows up: incompatible types when assigning to type 'struct a' from type 'int'. which I totally agree and understand.
But when declaring a pointer variable and assign it to an address:
1
2
3
4
5
6
7
#include <stdio>
#include <stdlib.h>
struct a
{int x,y;} *var;
int main(void)
{var=0x28ff1c;
return 0;}

This doesn't give any error, as if 0×28ff1c is of type struct a, but this doesn't make any sense. Can you please explain me the logic in as much details as possible? Thanks in advance!
Last edited on
This doesn't give any error, as if 0×28ff1c is of type struct a


var is of type pointer to a.
0x28ff1c is of type int.

Your compiler may convert one type to the other, though if you have enabled warning messages there should be some message from the compiler.

In C the statement could more properly be written as
 
    var = (struct a *)  0x28ff1c;

or in C++
 
    var = reinterpret_cast<a*>(0x28ff1c);
Last edited on
Yes, I was told about something about cast, but i wasn't sure of what cast i should put. Thanks!
Topic archived. No new replies allowed.