473,785 Members | 2,573 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Typecasting Pointers

Quick question:

if I have a structure:

struct foo {

unsigned char *packet;
unsigned char *ip_src;
};

and another structure:

struct foo2 {

unsigned char *packet;
};

and I do:

struct foo *a;
struct foo2 *b;

a = malloc(sizeof(s truct foo));
if (a == NULL)
return NULL;

(void)memset(a, 1, sizeof(struct foo));

b = (struct foo2 *)a;

--

Would foo2 just strip off the *packet?

And what happens to *ip?

I am trying to understand how C handles the typecast if
one structure pointed to has a different number of members
than the other. I am trying to understand how C99 treats
this situation. Both of my pointers should be correctly
aligned.

Thanks,

Brian
Nov 14 '05
13 2430
Barry Schwarz wrote:

[snip]
(void)memse t(a, 1, sizeof(struct foo));
This should be to 0 or NULL. My mistake.

Not really. NULL would not portable because some systems define NULL
to be (void*)0. 0 is not portable either since their is no guarantee
that a pointer value of all bits 0 has any meaning.


Then, what is the best way to initialize the structure? Should I even
bother? Now, I'm really stuck on this piece.

[snip]
There is only one address, the one returned by malloc. The fact that
you have stored this address in two different pointers doesn't change
that.
Awesome. I just wanted to confirm this to be true with that cast. I
wasn't sure after reading the standard.

[snip]
And I cannot dereference portably because the alignment restrictions
could be different?

Yup.


That stinks. I designed my program to have a structure in my header
file, and I used functions prototypes like

int somefunc(struct foo **);

to pass the structure around the program after allocating space for it.
Is there a portable way to pass variable values around a program?

Brian
Nov 14 '05 #11
On Thu, 25 Nov 2004 11:52:04 -0700, brian <tw*****@cox.ne t> wrote:
Barry Schwarz wrote:

[snip]
>(void)mems et(a, 1, sizeof(struct foo));

This should be to 0 or NULL. My mistake.

Not really. NULL would not portable because some systems define NULL
to be (void*)0. 0 is not portable either since their is no guarantee
that a pointer value of all bits 0 has any meaning.


Then, what is the best way to initialize the structure? Should I even
bother? Now, I'm really stuck on this piece.


If you define the structure, you can initialize it as part of the
definition:
struct foo a = {0};
This will cause each member of the struct to be set to the appropriate
zero value ('\0' for char, 0 for integers, 0.0 floating points, and
NULL for pointers.

If you allocate the struct, as was done up-thread, then you don't have
much choice but to do it member by member. However, if you have a
defined struct that was initialized, you can initialize the allocated
one by a simple assignment:
struct foo *b = malloc(sizeof *b);
b = a;

[snip]

There is only one address, the one returned by malloc. The fact that
you have stored this address in two different pointers doesn't change
that.
Awesome. I just wanted to confirm this to be true with that cast. I
wasn't sure after reading the standard.

[snip]
And I cannot dereference portably because the alignment restrictions
could be different?

Yup.


That stinks. I designed my program to have a structure in my header
file, and I used functions prototypes like


A header file should have only the struct declaration, not any
definition.

int somefunc(struct foo **);

to pass the structure around the program after allocating space for it.
Why would you use a pointer to pointer to struct when a simple pointer
to struct will let the function update the members at will? The
struct ** makes sense if the function will allocate the struct so it
can update the pointer directly but your comment says the struct is
already allocated.
Is there a portable way to pass variable values around a program?


Function arguments seem to work for most cases.

WHY do you want the address of a struct foo to be treated as the
address of a struct foo2? You might want to consider embedding both
structs in a union.
<<Remove the del for email>>
Nov 14 '05 #12
On Fri, 26 Nov 2004 23:06:37 -0800, Barry Schwarz <sc******@deloz .net>
wrote:
On Thu, 25 Nov 2004 11:52:04 -0700, brian <tw*****@cox.ne t> wrote:
Barry Schwarz wrote:

[snip]
>>(void)mem set(a, 1, sizeof(struct foo));

This should be to 0 or NULL. My mistake.
Not really. NULL would not portable because some systems define NULL
to be (void*)0. 0 is not portable either since their is no guarantee
that a pointer value of all bits 0 has any meaning.


Then, what is the best way to initialize the structure? Should I even
bother? Now, I'm really stuck on this piece.


If you define the structure, you can initialize it as part of the
definition:
struct foo a = {0};
This will cause each member of the struct to be set to the appropriate
zero value ('\0' for char, 0 for integers, 0.0 floating points, and
NULL for pointers.

If you allocate the struct, as was done up-thread, then you don't have
much choice but to do it member by member. However, if you have a
defined struct that was initialized, you can initialize the allocated
one by a simple assignment:
struct foo *b = malloc(sizeof *b);
b = a;


That should be *b = a;
<<Remove the del for email>>
Nov 14 '05 #13

In article <tZwpd.95065$SW 3.12565@fed1rea d01>, brian <tw*****@cox.ne t> writes:
Barry Schwarz wrote:
[brian wrote:]
>(void)memse t(a, 1, sizeof(struct foo));

This should be to 0 or NULL. My mistake.

Not really. NULL would not portable because some systems define NULL
to be (void*)0. 0 is not portable either since their is no guarantee
that a pointer value of all bits 0 has any meaning.


Then, what is the best way to initialize the structure? Should I even
bother? Now, I'm really stuck on this piece.


There are various alternatives, but I prefer structure assignment with
a static const initializer:

#include <stdlib.h>

static struct foo *alloc_foo(void )
{
static const struct foo foo0 = {0};
struct foo *newfoo = malloc(sizeof *newfoo);

if (newfoo)
*newfoo = foo0;

return newfoo;
}

The {0} is actually unnecessary, since static variables without an
explicit initializer are implicitly initialized to {0}, but I prefer
to make it explicit.

If multiple functions in a file need the initializer, put it at file
scope. If functions in multiple files need the initializer, you
could make it non-static, with an extern declaration in the header
that defines struct foo, but that raises issues of constraints on
and collisions of externally-visible names, so in some cases it may
be better simply to define one initializer per file (or refactor so
that only one file ever initializes dynamically-allocated variables
of that type - often the best choice).

By the way, returning to the question of Usenet signatures: your
messages should include a proper signature delimiter (a line
containing only two hyphens and a space) before your signature,
even if it only includes your name.

--
Michael Wojcik mi************@ microfocus.com

Is it any wonder the world's gone insane, with information come to be
the only real medium of exchange? -- Thomas Pynchon
Nov 14 '05 #14

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

Similar topics

63
3419
by: andynaik | last post by:
Hi, Whenever we type in this code int main() { printf("%f",10); } we get an error. We can remove that by using #pragma directive t direct that to the 8087. Even after that the output is 0.00000 and no 10.0000. Can anybody tell me why it is like that and why typecasting i not done in this case?
11
4425
by: Vinod Patel | last post by:
I have a piece of code : - void *data; ...... /* data initialized */ ...... struct known_struct *var = (struct known_struct*) data; /*typecasting*/ How is this different from simple assignment. int b = some_value;
3
3994
by: bnoordhuis | last post by:
Consider this: int foo(int *a, int *b); int (*bar)(void *, void *) = (void *)foo; How legal - or illegal - is the typecast and are there real-world situations where such code will cause trouble? I don't mean trouble like in 'not compiling' but trouble like in 'crashing hard'.
16
10400
by: Abhishek | last post by:
why do I see that in most C programs, pointers in functions are accepted as: int func(int i,(void *)p) where p is a pointer or an address which is passed from the place where it is called. what do you mean by pointing to a void and why is it done? Aso, what happens when we typecast a pointer to another type. say for example int *i=(char *)p; under different situations? I am kind of confused..can anybody clear this confusion by clearly...
12
8396
by: srinivas.satish | last post by:
Hi, is it possible to typecast a function pointer to two different prototypes. eg., typedef void (functptr1 *) (int , int); typedef void (functptr2 *) (int); functptr1 fptr; fptr = somefunction_name; fptr(10,20); fptr = (functptr2)someotherfunction_name;
5
11246
by: WittyGuy | last post by:
How to typecast a "function pointer" to "const void*" type in C++ way? int MyFunction (double money); // Function prototype const void* arg = (const void*)MyFunction; // type casting function pointer to const void* in C-style void(*pFunc)() = (void(*)())(arg); // type casting const void* to function pointer in C-style (*pFunc)(); // Calling the function after type casting is done
12
4481
by: bwaichu | last post by:
What is the best way to handle this warning: warning: cast from pointer to integer of different size I am casting in and out of a function that requires a pointer type. I am casting an integer as a pointer, but the pointer is 8 bytes while the integer is only 4 bytes. Here's an example function:
12
1731
by: chadsspameateremail | last post by:
What I am trying to do is implement polymorphism in C. Why? This is to build a library which will be a C library and callable from C. However, I want to have polymorphic functions which are callable from outside the library. Specifically I want to have functions like Show() which will take a pointer to an object and do something different based on the type object passed to it. Of course this would be trival in C++ but I'm restricted to use...
3
13131
by: sritejv | last post by:
Hello everyone, I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work. void *xyz; struct abcd { int a; };
0
9485
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
10356
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
10161
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
7506
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
6743
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
5390
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
4058
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
2
3662
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2890
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.