Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure Typecasting

Tags:

c

types

I have a

structure {
    int a;
    char b;
} st;

Is there a way to typecast the structure member st.a? Because in few places I want it as int and in few places I want it as Char*

like image 991
kiran Avatar asked Aug 15 '26 12:08

kiran


2 Answers

I suggest to use a union:

struct {
  union {
    int a;
    char *ptr;
  } u;
  char b;
} st;

Under the assumption that sizeof(int) == sizeof(char*) holds, you can access the same value in memory by either using st.u.a or st.u.ptr.

For what it's worth, consider using size_t instead of int as the type of the a field. That way, your code will still be correct in 64bit builds (in which an int may still be 32bit but a pointer is 64bit).

like image 169
Frerich Raabe Avatar answered Aug 17 '26 02:08

Frerich Raabe


What you want is called unions.

like image 42
Gerstmann Avatar answered Aug 17 '26 03:08

Gerstmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!