-6

What is the meaning of this statement in C?

struct foo *ptr = (struct foo *) p2;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Fagun
  • 35
  • 8

2 Answers2

2

You're not giving all the informations we need:

struct name *ptr = (Same struct name *) p2;

let's make it something that can compile:

struct foo* ptr = (struct foo*) p2;

but now we're missing what p2 is. So, I'm going to assume that p2 is a plain C pointer, i.e. void*:

void* p2;
struct foo* ptr = (struct foo*) p2;

So here you're assigning to ptr the address pointed by p2. In my example now, this is pretty pointless… but if you allocate some memory:

void* p2 = malloc(sizeof(struct foo));
struct foo* ptr = (struct foo*) p2;

then p2 is having the address of a memory space that then you assign to ptr.

The example I'm giving you here is using two variables for doing the usual:

struct foo* ptr = (struct foo*) malloc(sizeof(struct foo));
zmo
  • 24,463
  • 4
  • 54
  • 90
  • UINT32 p2; is the type – Fagun Jan 28 '14 at 13:36
  • 1
    Since void* can be assigned to any pointer casting examples are kinda irrelevant. – this Jan 28 '14 at 13:37
  • [looks like it is considered to be](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) though I've been taught to cast my mallocs at uni, and I think there are some compilers complaining about this when you do `-Wall`. – zmo Jan 28 '14 at 13:37
  • No C compiler should ever complain about casting from `void*` – David Heffernan Jan 28 '14 at 13:38
  • Not if they are standard compliant. Casting is only useful when using C++ compiler for C code, which is a bad idea to begin with. – Jori Jan 28 '14 at 13:38
  • ok, good to know, Jori. Though there are some cases where you have a C++ compiler and the only way to allocate memory is to use `malloc()` (as new is not existing). I'm thinking of AVR embedded development. But I'd agree that's an exception… – zmo Jan 28 '14 at 13:38
2

Starting at the left hand side:

struct foo *ptr

declares ptr to be of type struct foo *, that is a pointer to struct foo.

The = initializes that ptr variable to whatever the right hand side evaluates as.

And the right hand side

(struct foo *) p2

is an expression that casts p2 to be of type struct foo *.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490