473,698 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer to Structure Casts

I am working with some code that is doing some pointer to structure
casts and I can't figure out how the cast is being done. Here is
basically the code.

#include <stdio.h>
#include <stdlib.h>

typedef struct diffRecord
{
struct record *next[1];
} DiffRecord;

typedef struct record
{
struct record *next;
int value;
} Record;

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
rec1->value = 5;

Record *rec2 = malloc(sizeof(R ecord));
rec2->value = 6;

rec1->next = rec2;
rec2->next = NULL;

DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
Record *testRec = (Record*)diffRe c;

printf("The value is: %i\n", testRec->value); //prints 6

free(rec1);
free(rec2);

return 0;
}

How is the pointer contained in record being coerced into the array in
the diffRecord structure?

Caleb Van Dyke

Nov 15 '05 #1
5 2312
On 20 Sep 2005 17:11:02 -0700, "ca***********@ gmail.com"
<ca***********@ gmail.com> wrote:
I am working with some code that is doing some pointer to structure
casts and I can't figure out how the cast is being done. Here is
basically the code.
The cast is being done by the statements that contain the casts. What
can't you figure out?
#include <stdio.h>
#include <stdlib.h>

typedef struct diffRecord
{
struct record *next[1];
} DiffRecord;

typedef struct record
{
struct record *next;
int value;
} Record;

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
rec1->value = 5;

Record *rec2 = malloc(sizeof(R ecord));
Many C compilers do not allow definitions to follow executable
statements within a block. (It did not become a standard feature
until C99 and there aren't many C99 compilers in use.) By not putting
all your definitions at the start of the block you reduce the number
of people in the group who can help you.
rec2->value = 6;

rec1->next = rec2;
rec2->next = NULL;
You now have a linked list with two elements.

DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
Take the value in rec1 which has the type pointer to Record and
convert it by whatever means is appropriate for your system to point
to the same address but with type pointer to DiffRecord. Since next
and next[] are the first members of their respective structs, you are
guaranteed there is no padding before them so this code will pick up
the pointer that has offset 0 into the struct.

This is a bad idea. It is probable that Record and DiffRecord have
the same alignment but why run the risk. If the value in rec1 is not
suitably aligned for a DiffRecord, this would invoke undefined
behavior.
Record *testRec = (Record*)diffRe c;
Do the same thing in the opposite direction.

Since the standard requires all pointers to struct to have the same
size and representation, the value will always be the same address but
the type is changing.

printf("The value is: %i\n", testRec->value); //prints 6

free(rec1);
free(rec2);

return 0;
}

How is the pointer contained in record being coerced into the array in
the diffRecord structure?
It isn't. rec1 is being treated as if it points to a DiffRecord.
next[0] is a pointer which occupies the beginning of the struct. rec1
actually points to a Record. "It just so happens" that the beginning
of this struct is also occupied by a pointer of the same type.

It's still a lousy idea. If you change value from an int to a double
you would invoke undefined behavior on my system.

Caleb Van Dyke

<<Remove the del for email>>
Nov 15 '05 #2
<ca***********@ gmail.com> wrote in message
news:11******** *************@g 49g2000cwa.goog legroups.com...
I am working with some code that is doing some pointer to structure
casts and I can't figure out how the cast is being done. Here is
basically the code. .... typedef struct diffRecord
{
struct record *next[1];
} DiffRecord;

typedef struct record
{
struct record *next;
int value;
} Record;

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
rec1->value = 5;

Record *rec2 = malloc(sizeof(R ecord));
rec2->value = 6;

rec1->next = rec2;
rec2->next = NULL;

DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
Record *testRec = (Record*)diffRe c;

printf("The value is: %i\n", testRec->value); //prints 6 .... How is the pointer contained in record being coerced into the array in
the diffRecord structure?


Here:
struct record *next[1];
struct record *next;
One struct contains array of 1 pointer.
The other contains 1 pointer, w/o being part of any array.
But, they both contain a pointer anyway, so there's no problem here. It's
not much different from the case when you have an array of 1 int and just 1
int, simply the type is different.
So, both structs contain in their beginning a pointer (or array of one
pointer -- doesn't matter how you think of it, in this particular case it's
essentially the same thing and from the memory's standpoint the two things
are equivalent)...
I can only say that this is a bit odd code... I'd expect this way of casting
Record *testRec = (Record*)diffRe c;
rather than this
DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
But you have both. What for?

Alex
Nov 15 '05 #3
Alexei A. Frounze wrote:
<ca***********@ gmail.com> wrote in message
news:11******** *************@g 49g2000cwa.goog legroups.com...
I am working with some code that is doing some pointer to structure
casts and I can't figure out how the cast is being done. Here is
basically the code.

...
typedef struct diffRecord
{
struct record *next[1];
} DiffRecord;

typedef struct record
{
struct record *next;
int value;
} Record;

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
rec1->value = 5;

Record *rec2 = malloc(sizeof(R ecord));
rec2->value = 6;

rec1->next = rec2;
rec2->next = NULL;

DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
Record *testRec = (Record*)diffRe c;

printf("The value is: %i\n", testRec->value); //prints 6

...
How is the pointer contained in record being coerced into the array in
the diffRecord structure?


Here:
struct record *next[1];
struct record *next;
One struct contains array of 1 pointer.
The other contains 1 pointer, w/o being part of any array.
But, they both contain a pointer anyway, so there's no problem here. It's
not much different from the case when you have an array of 1 int and just 1
int, simply the type is different.
So, both structs contain in their beginning a pointer (or array of one
pointer -- doesn't matter how you think of it, in this particular case it's
essentially the same thing and from the memory's standpoint the two things
are equivalent)...
I can only say that this is a bit odd code... I'd expect this way of casting
Record *testRec = (Record*)diffRe c;
rather than this
DiffRecord *diffRec = ((DiffRecord*)r ec1)->next[0];
But you have both. What for?

Alex


This code actually is from another author. Their code looks something
like this:

#include <stdio.h>
#include <stdlib.h>

typedef struct diffRecord
{
struct diffRecord *next[2];
} DiffRecord;

typedef struct record
{
struct record *next;
struct record *previous;
int value;
} Record;

static void printValue(int index, Record *rec)
{
DiffRecord *diffRec = (DiffRecord*)re c;
Record *testRec = (Record*)diffRe c->next[index];
printf("Value: %i\n", testRec->value);
}

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
Record *rec2 = malloc(sizeof(R ecord));
Record *rec3 = malloc(sizeof(R ecord));

rec1->value = 5;
rec2->value = 6;
rec3->value = 7;

rec1->next = rec2;
rec1->previous = NULL;

rec2->previous = rec1;
rec2->next = rec3;

rec3->previous = rec2;
rec3->next = NULL;

printValue(0, rec2);
printValue(1, rec2);

free(rec3);
free(rec2);
free(rec1);

return 0;
}

Output:
Value: 7
Value: 5

I think their intention was for the parameter index in printValue() to
be some sort of selector for the pointers in the rec parameter. The
haven't seen a cast like this before but I am assuming that this works
becuase the first two parameters of Record are pointers?

If say Record looks like this:

typedef struct record
{
struct record *next;
int value;
struct record *previous;
} Record;

and I cast struct record to a struct diffRecord would I get some
undefined behaviour trying to access next[1] field of diffRecord?

Thanks for the help,
Caleb Van Dyke

Nov 15 '05 #4
On 21 Sep 2005 17:27:45 -0700, "ca***********@ gmail.com"
<ca***********@ gmail.com> wrote:

snip ~60 lines of code you now tell us is irrelevant. Please trim
your posts.

This code actually is from another author. Their code looks something
like this:

#include <stdio.h>
#include <stdlib.h>

typedef struct diffRecord
{
struct diffRecord *next[2];
next[0] will be followed immediately by next[1].
} DiffRecord;

typedef struct record
{
struct record *next;
struct record *previous;
But there is no guarantee that previous immediately follows next in
the memory occupied buy such a structure.
int value;
} Record;

static void printValue(int index, Record *rec)
{
DiffRecord *diffRec = (DiffRecord*)re c;
Record *testRec = (Record*)diffRe c->next[index];
printf("Value: %i\n", testRec->value);
This is still crappy code that could be solved without risk of
undefined behavior by code like
testRec = index ? rec->previous : rec->next;
}

int main(int argc, char* argv[])
{
Record *rec1 = malloc(sizeof(R ecord));
Record *rec2 = malloc(sizeof(R ecord));
Record *rec3 = malloc(sizeof(R ecord));

rec1->value = 5;
rec2->value = 6;
rec3->value = 7;

rec1->next = rec2;
rec1->previous = NULL;

rec2->previous = rec1;
rec2->next = rec3;

rec3->previous = rec2;
rec3->next = NULL;

printValue(0, rec2);
printValue(1, rec2);

free(rec3);
free(rec2);
free(rec1);

return 0;
}

Output:
Value: 7
Value: 5

I think their intention was for the parameter index in printValue() to
be some sort of selector for the pointers in the rec parameter. The
haven't seen a cast like this before but I am assuming that this works
becuase the first two parameters of Record are pointers?

If say Record looks like this:

typedef struct record
{
struct record *next;
int value;
struct record *previous;
} Record;

and I cast struct record to a struct diffRecord would I get some
undefined behaviour trying to access next[1] field of diffRecord?


Absolutely.
<<Remove the del for email>>
Nov 15 '05 #5
Barry Schwarz wrote:
On 21 Sep 2005 17:27:45 -0700, "ca***********@ gmail.com"
<ca***********@ gmail.com> wrote:

snip ~60 lines of code you now tell us is irrelevant. Please trim
your posts.


Sorry it's so long. I was trying to be concise. Thanks for answering my
question, but why do you think I am saying this is irrelevant? I was
trying to figure out the behavior of structure members when they are
cast to another structure. I only posted the revised code to show why
this weird cast was being done.

Caleb Van Dyke

Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5575
by: Robert Street | last post by:
Hi! I'm rather new at c++ and I'm totally confused with this kind of typecasting: typedef signed char int8_t; typedef signed short int16_t; typedef struct broadcast_hdr {
22
12730
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do exactly this, and similarly generic functions seem to have useful applications. In a few posts I read, it was suggested to avoid void pointer arithmetic by casting to a char pointer, and performing arithmetic on that (in multiples of...
3
2985
by: joe bruin | last post by:
hello all. i am trying to get rid of some warnings and do "the right thing". although in this particular case, i am not sure what the right thing is. the code: typedef struct {
3
1378
by: Mr. X | last post by:
Hello all, Please advise... Consider the following... void init_sockaddr (struct sockaddr_in *name, const char *hostname,int port) { struct hostent *hostinfo; name->sin_family = AF_INET;
26
7763
by: Alfonso Morra | last post by:
Hi, I'm getting a compiler error of "pointer truncation from 'void *' to 'int'" because I'm not explicitly casting from void* to (datatype*). Pointers are stored as ints (is that right?), so as AFAIK, there is nothing to worry about is there? I'm using VC 7.1 Why are such assignments being treated as errors?
40
3018
by: Steve Rencontre | last post by:
I can't for the life of me see how to do pointer-to-member when the member is actually part of an embedded structure. That is, if I have: struct S1 { int a; }; struct S2 { S1 s; int b; }; how can I get a pointer to the a in an S2?
27
8955
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in advance. Erik
49
2785
by: elmar | last post by:
Hi Clers, If I look at my ~200000 lines of C code programmed over the past 15 years, there is one annoying thing in this smart language, which somehow reduces the 'beauty' of the source code ;-): char *cp; void *vp; void **vpp;
17
5249
by: Ivan K. | last post by:
I am looking at some legacy code, which begins by allocating a double matrix with the dmatrix() function from NRC as follows: double **A, **augin, **augout, **aa; A = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3); aa = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3); augin = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3+MAXSIMS); augout = dmatrix(1, MAXNSTU+1, 1, MAXCOV+MAXCOVLOC+3+MAXSIMS);
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9028
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8861
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7728
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2330
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2001
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.