2

I'm trying to typecast a struct, with a pointer member, to (char *). Please tell me if there is any difference between the below two typecasting strategies. The struct is also shown.

struct videoPacket{
    uchar * videoData;
}video;

// and initializing 'video' to some value

Strategy 1:

videoPacket * videoPointer = &video;
char * buffer = (char *)videoPointer;

Strategy 2:

videoPacket * videoPointer = &video;
char * buffer = (char *)videoPointer->videoData;

Since the struct has a single member, will the buffer not point to the same contents?

EDIT: If i want to typecast the struct shown below to char *, how do i do it?

struct struct1{
    uchar * struct1data1;
        char struct1data2; 
}video;
Vigo
  • 707
  • 4
  • 11
  • 29
  • You could cast _anything_ to to `char*` with undefined behavior. – timrau May 09 '14 at 16:44
  • If you stop using C-style casts you'll find the first one requires a `reinterpret_cast` (which generally suggests you're doing something unwise), whereas the second works with `static_cast` which is less worrying. – Alan Stokes May 09 '14 at 16:50

2 Answers2

2

Strategy 1 is incorrect. It returns a pointer to the memory that stores the address of the data you want.

Strategy 2 is 'correct'. It returns the address of the data.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

It really does not matter which way you do it. And it is not the fact that your struct only has one member. It's the fact that the first member in your struct is uchar* videoData, so both "video" and "video.videoData" point to the same location in memory.

santahopar
  • 2,933
  • 2
  • 29
  • 50