Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast pointer to unnamed struct pointer?

Tags:

c++

I had this struct the other day:

struct foo_t {
  char a, b, c;
} *foo = (foo_t*)untyped_memory;

…but having a named type for it was excessive. However, its unnamed form:

struct {
  char a, b, c;
} *bar = untyped_memory;

...did not compile because of pointer types being incompatible.

Is there any way to make it work?

like image 334
Andreas Avatar asked Mar 28 '26 17:03

Andreas


1 Answers

If you have access to C++11 or above then you can use decltype i.e.

struct {
  char a, b, c;
} *bar = (decltype(bar))untyped_memory;
like image 126
George Avatar answered Apr 02 '26 19:04

George



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!