473,498 Members | 1,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

type casting a pointer (to a structure) to a pointer (to a different structure)

2 New Member
Hi,
I am sturggling with a peace of code mainly its about casting a pointer to one type of structure to a pointer to another type of structure.

the confusion begins with the following line...(modified to highlight the actual prob)

#define TEST_MACRO(first) ((struct second *) &first[1])

/*here it would return a pointer to second, but the question is why it uses [1]
Here in this example "first" and "second" are two different structures*/

Then later in the code:

void somefucntion (struct first * fptr)
{
struct second * sptr= TEST_MACRO(fptr);

/*then they use sptr to access various fields in the second structure e.g */

a_pointer= sptr->first_element;

.
.
.

Now my question is that after typecasting a pointer of one type of structure to another one, how can we use that (in this case the sptr) to access its members, i mean how values are assigned to them just by typecasting one pointer to another and in this case they are completly different structures. Thanks in advance!

Regards,
Khan
Mar 30 '08 #1
4 15158
Ganon11
3,652 Recognized Expert Specialist
Are they different structs with the same basic structure? i.e.

Expand|Select|Wrap|Line Numbers
  1. struct first {
  2.    int myInt;
  3.    char myChar;
  4.    double myDouble;
  5.    string myName;
  6. };
  7.  
  8. struct second {
  9.    int myInt;
  10.    char myChar;
  11. };
If so, you should probably be able to access the members of second normally. Of course, this will be messed up if you use an array of second structs - in that case, you'll be changing the myDouble and myName values with every new second struct.

I'd have to ask, though, why you have to be typecasting to different pointer types?
Mar 30 '08 #2
Schkhan
2 New Member
Are they different structs with the same basic structure? i.e.

Expand|Select|Wrap|Line Numbers
  1. struct first {
  2.    int myInt;
  3.    char myChar;
  4.    double myDouble;
  5.    string myName;
  6. };
  7.  
  8. struct second {
  9.    int myInt;
  10.    char myChar;
  11. };
If so, you should probably be able to access the members of second normally. Of course, this will be messed up if you use an array of second structs - in that case, you'll be changing the myDouble and myName values with every new second struct.

I'd have to ask, though, why you have to be typecasting to different pointer types?
Many thanks for your reply. Let me clarify things a little bit,
these are two completly different structures. the initial point of confustion is in the macro,
#define TEST_MACRO(first) ((struct second *) &first[1])

it essentially returns a pointer to a structure of type "second", but why they are using an index value, i mean they could have done it like
#define TEST_MACRO(first) ((struct second *) &first)

the next point of confusion is that after we use
void somefucntion (struct first * fptr)
{
struct second * sptr= TEST_MACRO(fptr);

a_pointer= sptr->first_element;



the confusion here is that how can we access a member of "second" through sptr just by typecasting a pointer of type "first" and in this case their sizes are different. can you provide an insight into this. Thanks in advance.

regards,
Khan
Mar 31 '08 #3
Banfa
9,065 Recognized Expert Moderator Expert
A reason you might do this is if the pointer to first actually represents the handle of a piece of memory (probably allocated from the heap) which contains at least 2 structures or areas which in this case are defined differently.

You know that the second structure appears immediately after the first structure in memory but only have the pointer to the first (because that is easy to use as a handle). This might be fairly common in an ADT

Example
Expand|Select|Wrap|Line Numbers
  1. struct PublicData {
  2.     char Name[20];
  3. };
  4.  
  5. struct PrivateData {
  6.     void *buffer;
  7.     int buffer_type;
  8. }
  9.  
  10. struct PublicData *Create(char *Name)
  11. {
  12.     PublicData *ppd;
  13.  
  14.     pPublic = malloc(sizeof(struct PublicData) + sizeof(struct PrivateData));
  15.  
  16.     if (pPublic != NULL)
  17.     {
  18.         strcpy(pPublic->Name, Name);
  19.  
  20.         /* Code to fill in private data */
  21.     }
  22.  
  23.     return pPublic;
  24. }
  25.  
  26. int GetSizestruct PublicData *pPublic)
  27. {
  28.     int size;
  29.     /* calculate pointer to private data from public data */
  30.     struct PrivateData *pPrivate = (struct PrivateData *)&pPublic[1];
  31.  
  32.     /* Use pPrivate to calculate size of data */
  33.  
  34.    return size;
  35. }
Bascially the construct uses pointer arithmatic to find the location immediately following the first structure, it knows this is the second structure so it casts the pointer to the correct type.

I believe this is platform defined behaviour, that is you have no guarantee that casting a pointer to 1 type to a pointer to another is going to work as expected(except for TYPE * to void * and then void * to TYPE *). However it does seem to work fine on many platforms.
Mar 31 '08 #4
Banfa
9,065 Recognized Expert Moderator Expert
#define TEST_MACRO(first) ((struct second *) &first[1])

it essentially returns a pointer to a structure of type "second", but why they are using an index value, i mean they could have done it like
#define TEST_MACRO(first) ((struct second *) &first)
No they couldn't these 2 macros are not equivalent, your 2nd macro here is equivalent to

#define TEST_MACRO(first) ((struct second *) &first[0])

Arrays index from 0 remember
Mar 31 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

3
5807
by: Cgacc20 | last post by:
I have a c struct from old code that cannot be modified and I am trying to write a wrapper C++ class around it. This class is often passed as a pointer to some c functions of a library and I...
4
3438
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A...
20
2591
by: pinkfloydhomer | last post by:
Is it well-defined and portable to do something like: typedef struct { int type; char c; } S1; typedef struct {
31
3108
by: dragoncoder | last post by:
Consider the code class A { private: int a; }; int main(void) { A x; int* ptr = (int*)&x;
9
430
by: Roman Mashak | last post by:
Hello, All! I met this code recently on some open source sites. What may be the point of using such construction: typedef struct cmd { unsigned int cmdack; unsigned int code; unsigned int...
11
32207
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? ...
41
4918
by: SRR | last post by:
Why is it discouraged to explicitly typecast the void pointer returned by malloc(); function? For example: { int *p; p = (int*)malloc(2*sizeof(int)); /*Explicit casting is done, therfore it...
3
1875
by: =?Utf-8?B?amFtZXNAbm9zcGFtLmNvbQ==?= | last post by:
I have an existing MFC c++ ocx control that I need to work with a c# class. If I use a locally defined data structure, everything works. For example, in my C++ app I declare. MyCSharpClass...
3
5449
by: Nasif | last post by:
Dear All I am using a C++ DLL which has two function , one returns a void pointer, other returns a pointer to structure .But I doing my project on C#. Which data types in C# should I use to...
0
7002
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7203
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4908
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4588
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3081
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1417
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
290
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.