473,651 Members | 3,012 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting struct to char array (was: Linked List problem)


"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message news:41******** ********@news.i ndividual.net.. . to news:comp.lang. c
be******@hotmai l.com (Ben) wrote:

[snip]
2) Structure casted into an array of char
typedef struct {
char name[20];
int age;
int id;
} person;

person p = (person *) malloc(sizeof(p erson));
p.name="hello";
p.age=2;
p.id=2;

char *a;
a=(char *)p;


No. You cannot cast a struct into a pointer. And what would you do this
for, anyway? Do you suppose that the bytes represented by "hello"
somehow form a valid pointer?
I suspect you meant to access the struct itself _through_, not _as_, a
pointer to char. In that case, you need to do

a = (char *)&p;

which is perfectly legal, and can be useful - though rarely. Beware the
padding bytes!

[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Jul 22 '05 #1
5 9732
Alex Vinokur wrote:
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message news:41******** ********@news.i ndividual.net.. . to news:comp.lang. c
be******@hotm ail.com (Ben) wrote:


[snip]
2) Structure casted into an array of char
typedef struct {
char name[20];
int age;
int id;
} person;

person p = (person *) malloc(sizeof(p erson));
p.name="hell o";
p.age=2;
p.id=2;

char *a;
a=(char *)p;


No. You cannot cast a struct into a pointer. And what would you do this
for, anyway? Do you suppose that the bytes represented by "hello"
somehow form a valid pointer?
I suspect you meant to access the struct itself _through_, not _as_, a
pointer to char. In that case, you need to do

a = (char *)&p;

which is perfectly legal, and can be useful - though rarely. Beware the
padding bytes!


[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?


Which "padding problem" is it?

V
Jul 22 '05 #2

"Victor Bazarov" <v.********@com Acast.net> wrote in message news:Bq******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Alex Vinokur wrote:
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message news:41******** ********@news.i ndividual.net.. . to news:comp.lang. c
be******@hotm ail.com (Ben) wrote:


[snip]
2) Structure casted into an array of char
typedef struct {
char name[20];
int age;
int id;
} person;

person p = (person *) malloc(sizeof(p erson));
p.name="hell o";
p.age=2;
p.id=2;

char *a;
a=(char *)p;

No. You cannot cast a struct into a pointer. And what would you do this
for, anyway? Do you suppose that the bytes represented by "hello"
somehow form a valid pointer?
I suspect you meant to access the struct itself _through_, not _as_, a
pointer to char. In that case, you need to do

a = (char *)&p;

which is perfectly legal, and can be useful - though rarely. Beware the
padding bytes!


[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?


Which "padding problem" is it?

V

--------- C++ code : BEGIN ---------
// File foo.cpp
#include <iostream>
using namespace std;

struct Foo1
{
char ch1;
char ch2;
short sh1;
Foo1 () : ch1 ('a'), ch2('b'), sh1 (0x6364) {};

};

struct Foo2
{
char ch1;
short sh1;
char ch2;
Foo2 () : ch1 ('a'), sh1 (0x6364), ch2('b') {};

};
#define SHOW(x,i) cout << #x << "[" << i << "] = " << x[i] << endl

int main ()
{
Foo1 foo1;
Foo2 foo2;
char* charray1 = (char*)&foo1;
char* charray2 = (char*)&foo2;

cout << "Foo1" << endl;
SHOW (charray1, 0);
SHOW (charray1, 1);
SHOW (charray1, 2);
SHOW (charray1, 3);

cout << endl;
cout << "Foo2" << endl;
SHOW (charray2, 0);
SHOW (charray2, 1);
SHOW (charray2, 2);
SHOW (charray2, 3);
SHOW (charray2, 4);

return 0;
}
--------- C++ code : END -----------

--------- Compilation & Run : BEGIN ---------

$ g++ -v
[omitted]
gcc version 3.3.3 (cygwin special)
$ g++ -W -Wall foo.cpp
// No errors/warnings

$ a

Foo1
charray1[0] = a
charray1[1] = b
charray1[2] = d
charray1[3] = c

Foo2
charray2[0] = a
charray2[1] = ~
charray2[2] = d
charray2[3] = c
charray2[4] = b

--------- Compilation & Run : END -----------

We can see that ch2 from Foo1 and Foo2 is in the different places of charray1 and charray2
because charray2[1] is a hole.
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Jul 22 '05 #3
Alex Vinokur wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:Bq******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Alex Vinokur wrote:
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message news:41******** ********@news.i ndividual.net.. . to news:comp.lang. c
be******@ho tmail.com (Ben) wrote:

[snip]
>2) Structure casted into an array of char
>typedef struct {
>char name[20];
>int age;
>int id;
>} person;
>
>person p = (person *) malloc(sizeof(p erson));
>p.name="he llo";
>p.age=2;
>p.id=2;
>
>char *a;
>a=(char *)p;

No. You cannot cast a struct into a pointer. And what would you do this
for, anyway? Do you suppose that the bytes represented by "hello"
somehow form a valid pointer?
I suspect you meant to access the struct itself _through_, not _as_, a
pointer to char. In that case, you need to do

a = (char *)&p;

which is perfectly legal, and can be useful - though rarely. Beware the
padding bytes!
[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?


Which "padding problem" is it?

V


--------- C++ code : BEGIN ---------
// File foo.cpp
#include <iostream>
using namespace std;

struct Foo1
{
char ch1;
char ch2;
short sh1;
Foo1 () : ch1 ('a'), ch2('b'), sh1 (0x6364) {};

};

struct Foo2
{
char ch1;
short sh1;
char ch2;
Foo2 () : ch1 ('a'), sh1 (0x6364), ch2('b') {};

};

[...]

--------- Compilation & Run : END -----------

We can see that ch2 from Foo1 and Foo2 is in the different places of charray1 and charray2
because charray2[1] is a hole.


OK, I'll bite. How is that a problem? If your struct is a POD, you may
use 'offsetof' to figure out where exactly a member is, but if it's not
POD, what use do you have for the "position"?

V
Jul 22 '05 #4

"Victor Bazarov" <v.********@com Acast.net> wrote in message news:t8******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Alex Vinokur wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:Bq******** ********@newsre ad1.dllstx09.us .to.verio.net.. .
Alex Vinokur wrote:

"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message news:41******** ********@news.i ndividual.net.. . to news:comp.lang. c
>be******@ho tmail.com (Ben) wrote:

[snip]
>>2) Structure casted into an array of char
>>typedef struct {
>>char name[20];
>>int age;
>>int id;
>>} person;
>>
>>person p = (person *) malloc(sizeof(p erson));
>>p.name="he llo";
>>p.age=2;
>>p.id=2;
>>
>>char *a;
>>a=(char *)p;
>
>No. You cannot cast a struct into a pointer. And what would you do this
>for, anyway? Do you suppose that the bytes represented by "hello"
>somehow form a valid pointer?
>I suspect you meant to access the struct itself _through_, not _as_, a
>pointer to char. In that case, you need to do
>
> a = (char *)&p;
>
>which is perfectly legal, and can be useful - though rarely. Beware the
>padding bytes!
>

[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?

Which "padding problem" is it?

V


--------- C++ code : BEGIN ---------
// File foo.cpp
#include <iostream>
using namespace std;

struct Foo1
{
char ch1;
char ch2;
short sh1;
Foo1 () : ch1 ('a'), ch2('b'), sh1 (0x6364) {};

};

struct Foo2
{
char ch1;
short sh1;
char ch2;
Foo2 () : ch1 ('a'), sh1 (0x6364), ch2('b') {};

};

[...]

--------- Compilation & Run : END -----------

We can see that ch2 from Foo1 and Foo2 is in the different places of charray1 and charray2
because charray2[1] is a hole.


OK, I'll bite. How is that a problem? If your struct is a POD, you may
use 'offsetof' to figure out where exactly a member is, but if it's not
POD, what use do you have for the "position"?

V


Something like ?
--------- C++ code : BEGIN ---------

#include <iostream>
#include <cassert>
using namespace std;

struct Foo
{
char ch1;
short sh;

char ch2;
char cstr[3];

char ch3;

Foo () : ch1 ('a'), sh (0x6667), ch2('b'), ch3('c') { strcpy (cstr, "de");};

operator char *()
{
const int pure_size (sizeof(ch1) + sizeof(sh) + sizeof(ch2) + strlen(cstr) + sizeof(ch3) + 1);
char* ret_ptr = new char [pure_size];

int i = 0;
ret_ptr[i++] = ch1;

char* tmp_ptr = (char*)&sh;
for (int j = 0; j < sizeof(sh); j++) ret_ptr[i++] = *tmp_ptr++;
ret_ptr[i++] = ch2;

for (int j = 0; j < strlen(cstr); j++) ret_ptr[i++] = cstr[j];

ret_ptr[i++] = ch3;
ret_ptr[i] = 0;
assert (i < pure_size);

return ret_ptr;

};

};
#define SHOW(x,i) cout << #x << "[" << i << "] : ch = " << x[i] << "; hex = " << hex << uint (x[i]) << endl

int main ()
{
Foo foo;
char* charray1 = (char*)&foo;
char* charray2 = (char*)foo;

cout << "Regular (char*)" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray1, i);

cout << endl;
cout << "Overloaded (char*)" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray2, i);

return 0;
}

--------- C++ code : END -----------

--------- Compilation & Run : BEGIN ---------

$ g++ -v
[omitted]
gcc version 3.3.3 (cygwin special)
$ g++ foo.cpp
// No errors/warnings

$ a

Regular (char*)
charray1[0] : ch = a; hex = 61
charray1[1] : ch = ; hex = 3
charray1[2] : ch = g; hex = 67
charray1[3] : ch = f; hex = 66
charray1[4] : ch = b; hex = 62
charray1[5] : ch = d; hex = 64
charray1[6] : ch = e; hex = 65
charray1[7] : ch = ; hex = 0
charray1[8] : ch = c; hex = 63
charray1[9] : ch = ð; hex = fffffff0

Overloaded (char*)
charray2[0] : ch = a; hex = 61
charray2[1] : ch = g; hex = 67
charray2[2] : ch = f; hex = 66
charray2[3] : ch = b; hex = 62
charray2[4] : ch = d; hex = 64
charray2[5] : ch = e; hex = 65
charray2[6] : ch = c; hex = 63
charray2[7] : ch = ; hex = 0
charray2[8] : ch = ; hex = 0
charray2[9] : ch = ; hex = 0

--------- Compilation & Run : END -----------
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn


Jul 22 '05 #5

"Alex Vinokur" <al****@big-foot.com> wrote in message news:2u******** *****@uni-berlin.de...
[snip]
-----------------------
For not POD
Something like ?

-----------------------
[snip]
For POD

--------- C++ code : BEGIN ---------
#include <iostream>
#include <cassert>
using namespace std;

struct Foo
{
char ch1;
short sh;

char ch2;
char cstr[3];

char ch3;

};

char* get_as_cstr(con st Foo& foo_i)
{
const int pure_size (sizeof(foo_i.c h1) + sizeof(foo_i.sh ) + sizeof(foo_i.ch 2) + strlen(foo_i.cs tr) + sizeof(foo_i.ch 3) + 1);
char* ret_ptr = new char [pure_size];

int i = 0;
ret_ptr[i++] = foo_i.ch1;

char* tmp_ptr = (char*)&foo_i.s h;
for (int j = 0; j < sizeof(foo_i.sh ); j++) ret_ptr[i++] = *tmp_ptr++;
ret_ptr[i++] = foo_i.ch2;

for (int j = 0; j < strlen(foo_i.cs tr); j++) ret_ptr[i++] = foo_i.cstr[j];

ret_ptr[i++] = foo_i.ch3;
ret_ptr[i] = 0;
assert (i < pure_size);

return ret_ptr;
}
#define SHOW(x,i) cout << #x << "[" << i << "] : ch = " << x[i] << "; hex = " << hex << uint (x[i]) << endl

int main ()
{
Foo foo;
foo.ch1 = 'a';
foo.sh = 0x6667;
foo.ch2 = 'b';
strcpy (foo.cstr, "de");
foo.ch3 = 'c';

char* charray1 = (char*)&foo;
char* charray2 = get_as_cstr (foo);

cout << "POD : Regular (char*)" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray1, i);

cout << endl;
cout << "POD : Function get_as_cstr" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray2, i);

return 0;
}
--------- C++ code : END -----------

--------- Compilation & Run : BEGIN ---------

$ g++ -v
[omitted]
gcc version 3.3.3 (cygwin special)
$ g++ foo.cpp
// No errors/warnings

$ a

POD : Regular (char*)
charray1[0] : ch = a; hex = 61
charray1[1] : ch = ; hex = 3
charray1[2] : ch = g; hex = 67
charray1[3] : ch = f; hex = 66
charray1[4] : ch = b; hex = 62
charray1[5] : ch = d; hex = 64
charray1[6] : ch = e; hex = 65
charray1[7] : ch = ; hex = 0
charray1[8] : ch = c; hex = 63
charray1[9] : ch = ð; hex = fffffff0

POD : Function get_as_cstr
charray2[0] : ch = a; hex = 61
charray2[1] : ch = g; hex = 67
charray2[2] : ch = f; hex = 66
charray2[3] : ch = b; hex = 62
charray2[4] : ch = d; hex = 64
charray2[5] : ch = e; hex = 65
charray2[6] : ch = c; hex = 63
charray2[7] : ch = ; hex = 0
charray2[8] : ch = ; hex = 0
charray2[9] : ch = ; hex = 0

--------- Compilation & Run : END -----------
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Jul 22 '05 #6

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

Similar topics

8
8901
by: rihad | last post by:
Hi, I've this question: suppose we have two differently typed pointers: struct foo *foo; char **array; Becase one can always legally cast any pointer to (void *), and becase (void *) is assignable to any pointer type, is it ever necessary to cast when assigning one pointer type to another? I.e. since foo = (void *) array;
20
2098
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
2
2027
by: Neil McPhail | last post by:
I'm new to C (and Usenet) and have been using the dreaded Schildt's Complete C Reference. I appreciate this may not have been the best idea, so no need to point this out! On page 546 there is a mailing list program with a struct defined thus: struct address { char name; char street; char city;
67
10706
by: S.Tobias | last post by:
I would like to check if I understand the following excerpt correctly: 6.2.5#26 (Types): All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Does it mean that *all* structure (or union) types have the same alignment? Eg. type
1
1878
by: rahul8143 | last post by:
hello, In kernel source code there is ip_fragment.c file my question is regarding pointer function and casting for that look at required snippet from that file There is structure defined for queueing ip fragments as struct ipq { struct ipq *next; /* linked list pointers */ struct list_head lru_list; /* lru list member */ u32 user; u32 saddr;
4
4503
by: kelli | last post by:
i am new to c# so if this is a trivial problem, forgive me! i've searched the web and after 2 days still cannot solve it. i am converting a c++ application to c# - the problem code is listed below. the c++ code uses a byte array (msg) to hold a serial message. since the message can be of different layouts, the array is cast to the appropriate layout "type" (struct SERIAL_CAN_MSG_TYPE, in this example). to complicate things, there is an...
9
2250
by: Erik | last post by:
Hi, i have this struct and this linked list /* structure describing a book.*/ typedef struct { char code; char author; char title; int year; int reserved; } Book;
11
4693
by: redefined.horizons | last post by:
First, I would thank all of those that took the time to answer my question about creating an array based on a numeric value stored in a variable. I realize after reading the responses and doing some more research, that what I really need is known in C as a "dynamic array". Basically, you surpass the array notation and use pointers with memory obtained with malloc() or calloc(). I think this will do just what I needed. That has brought...
3
2967
by: dreiko466 | last post by:
(sorry about my english...) I am a newbie in C (3 month expierience) I have wrote a simple test programm in VS2005, what i do wrong?Please... In this programm i create a double linked list.Then pass its first block pointer inside the structure Array to Array ->first and the last block pointer inside the structure Array to Array ->last.So i can manipulate the double linked list as a dynamic array. The cells of this dynamic array are...
0
8361
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8278
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8807
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
8701
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...
1
8466
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8584
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
5615
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
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2701
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 we have to send another system

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.