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

Home Posts Topics Members FAQ

Casting a pointer to an int and back

Is it well-defined to make a cast from a pointer to an int and back?
Like:

typedef struct
{
int whatever;
} S;

int main(void)
{
S* s = malloc(sizeof(S ));
int i = (int) s;
S* t = (S*) i;
t.whatever = 42;
etc.
}

/David

Feb 22 '06 #1
24 2458

pi************@ gmail.com wrote:
Is it well-defined to make a cast from a pointer to an int and back?
No, it is not.

You may be lucky that it works on your implementation, but don't count
on it (i.e. it's not portable).

Some concerns:

- how do pointers map to integers?
- how do integers map to pointers (not necessarily same as above)?
- is an integer wide enough to hold an address value (even if above is
fine)?

Even if all of the above are fine for one implementation/architecture,
the may not be on others.

Just don't do it. Also, have a look at other things you got wrong,
below:
Like:
#include <stdlib.h>

Otherwise `malloc` is unknown.
typedef struct
{
int whatever;
} S;

int main(void)
{
S* s = malloc(sizeof(S ));
int i = (int) s;
S* t = (S*) i;
t.whatever = 42;
You certainly mean:

t->whatever = 42;

or

(*t).whatever = 42;
etc.
This is a syntax error.

Please post full, compileable, minimal examples.
}

--
BR, Vladimir

Feb 22 '06 #2
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
etc.


This is a syntax error.


Well spotted. Go to top of the pedants class.

Feb 22 '06 #3
pi************@ gmail.com wrote:
Is it well-defined to make a cast from a pointer to an
int and back?


I don't think so.

For example, on some platforms,
sizeof(int) = 4 and sizeof(void *) = 8
Feb 22 '06 #4
Richard G. Riley wrote:
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
etc.


This is a syntax error.


Well spotted. Go to top of the pedants class.


Yes! I finally made it!

Snipping relevant parts of the post is bad etiquette. I also said:
Please post full, compileable, minimal examples.


Which was the whole point. It's in the OP's interest, really.

--
BR, Vladimir

Feb 22 '06 #5
"pi************ @gmail.com" <pi************ @gmail.com> wrote:
# Is it well-defined to make a cast from a pointer to an int and back?
# Like:

You can cast to some integer, but not necessarily an int. However
because so much legacy code depends on this working, compilers
will generaly do whatever is necessary to make it work.

You shouldn't need to cast ints to/from pointers anymore unless
you need to enter absolute address or similar issues. (void*)
can be assigned any data pointer the same way int used to be
a universal pointer type.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Mention something out of a Charleton Heston movie, and suddenly
everybody's a theology scholar.
Feb 22 '06 #6
"pi************ @gmail.com" <pi************ @gmail.com> wrote:
Is it well-defined to make a cast from a pointer to an int and back?
Like:

typedef struct
{
int whatever;
} S;

int main(void)
{
S* s = malloc(sizeof(S ));
int i = (int) s;
S* t = (S*) i;
t.whatever = 42;
etc.
}


On two conditions:
- that the cast from pointer to int doesn't lose any information, i.e.,
that an int is wide enough to hold all pointer values;
- that the pointer is cast to int and then back to the _same_ pointer
type;
AFAICT this is well-defined.

The second condition, only you yourself have any influence over. Just
don't convert a pointer to an integer and then to a different pointer
type. In this case, you're OK.
The first depends on the platform. If you have C99, you may be able to
use (u)intptr_t, which are integer types (not necessarily ints) capable
of holding any void * value safely. Declare i as intptr_t, and cast s to
void * before assigning it to i, and back the other way 'round, too:

intptr i = (int)(void *)s;.
S *t = (void *)i;

You don't need a cast to (S *) in the second line, since a void * will
be automatically and correctly converted to any object pointer type.
Unfortunately, these types are optional, and they don't exist in C89 at
all. If it's unavailable to you, you may just have to resort to using
unsigned long (or unsigned long long) and hoping that that's large and
well-aligned enough. It probably is, but it's not guaranteed. If you
have intptr_t, use it.

Richard
Feb 22 '06 #7
SM Ryan wrote:
"pi************ @gmail.com" <pi************ @gmail.com> wrote:
# Is it well-defined to make a cast from a pointer to an int and back?
# Like:

You can cast to some integer, but not necessarily an int. However
because so much legacy code depends on this working, compilers
will generaly do whatever is necessary to make it work. I believe C99 provides a typedef that's guaranteed to be some sort of
int large enough to hold any sort of pointer.

You shouldn't need to cast ints to/from pointers anymore unless
you need to enter absolute address or similar issues. (void*)
can be assigned any data pointer the same way int used to be
a universal pointer type.


Feb 22 '06 #8
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
Richard G. Riley wrote:
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
>> etc.
>
> This is a syntax error.


Well spotted. Go to top of the pedants class.


Yes! I finally made it!

Snipping relevant parts of the post is bad etiquette. I also said:
> Please post full, compileable, minimal examples.


Which was the whole point. It's in the OP's interest, really.


The snipped part had no relevance on my pithy reply to your pedant
prize winning reply. The guy was asking a question about casting : not for a
code review or smart assed comments on "etc." being a syntx error.

The fact that he didnt put in the includes and did include the ".etc"
would, to me, indicate that he was pseudo coding a bit to get an
answer to the pertient question which was "can one cast between
pointers and ints". I'm sure many others would have made this leap in
logic too : it is, after all, a programming language group :)

Or do you insist on working, compilable code for all questions on
casts?

Come on. Admit it. You were over the top
Feb 22 '06 #9

Richard G. Riley wrote:
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
Richard G. Riley wrote:
On 2006-02-22, Vladimir S. Oka <no****@btopenw orld.com> wrote:
>> etc.
>
> This is a syntax error.

Well spotted. Go to top of the pedants class.
Yes! I finally made it!

Snipping relevant parts of the post is bad etiquette. I also said:
> Please post full, compileable, minimal examples.


Which was the whole point. It's in the OP's interest, really.


The snipped part had no relevance on my pithy reply to your pedant
prize winning reply. The guy was asking a question about casting : not for a
code review or smart assed comments on "etc." being a syntx error.


Which question I answered /first/, and than added a few comments as
well. What is your problem with this?
The fact that he didnt put in the includes and did include the ".etc"
would, to me, indicate that he was pseudo coding a bit to get an
answer to the pertient question which was "can one cast between
pointers and ints". I'm sure many others would have made this leap in
logic too : it is, after all, a programming language group :)
He obviously wasn't "pseudocodi ng". His "pseudocode " looked very much
like an attempt at a C program. It actually wasn't even required to
support his question, especially not with the struct.
Or do you insist on working, compilable code for all questions on
casts?
Not necessarily working (otherwise there'll be no question, right? ;-)
), but certainly compilable (and not just for the cast questions). Or,
do you always re-type the posted code to try it out?
Come on. Admit it. You were over the top


Continuing to indulge you? I admit to that.

--
BR, Vladimir

Feb 22 '06 #10

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

Similar topics

4
3467
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 good way to do this is by example. So I will give an example and please tell me what you think: I have a base class A with a virtual destructor, and a class B that is it inherits publicly from A and defines som extra stuff.
16
2433
by: He Shiming | last post by:
Hi, I'm having a little bit of trouble regarding pointer casting in my program. I don't understand why the following two cases produce different results. Case 1: IInterface *pInterface = new CImplementation(); pInterface->Method(); Case 2:
8
5657
by: wkaras | last post by:
In my compiler, the following code generates an error: union U { int i; double d; }; U u; int *ip = &u.i; U *up = static_cast<U *>(ip); // error I have to change the cast to reinterpret_cast for the code
31
3171
by: dragoncoder | last post by:
Consider the code class A { private: int a; }; int main(void) { A x; int* ptr = (int*)&x;
33
3646
by: Mark P | last post by:
A colleague asked me something along the lines of the following today. For some type X he has: X* px = new X; Then he wants to convert px to a char* (I'm guessing for the purpose of serializing the object array). I can think of three ways to do this:
3
3651
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
8
4266
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is not valid"). How do I fix it ? using System.Diagnostics; .. .. class NewProcess: Process {
7
2646
by: William S Fulton | last post by:
I'm looking for the name of the following casting style in order to do some reading around on it and why it is sometimes used. unsigned long long ull = 0; void * ptr = 0; ull = *(unsigned long long*)&ptr; As opposed to the more usual casting:
5
5925
by: brekehan | last post by:
I've always been a little sketchy on the differences between static, dynamic, and reinterpret casting. I am looking to clean up the following block by using C++ casting instead of the C style casting. from what I am reading, I should use reinterpret cast in this situation, is that correct? Why does static and dynamic casting fail me? // please excuse the windows types, it is necessary in this code, // but the question remains C++ related
9
2455
by: Jess | last post by:
Hello, It seems both static_cast and dynamic_cast can cast a base class pointer/reference to a derived class pointer/reference. If so, is there any difference between them? In addition, if I have a derived class object and then upcast it to its base class, which cast operator should I use? Is it static_cast, or, can I simply cast it implicitly without any operator? Does this upcasting remove the derived class portion of the object?...
0
8674
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
9027
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
8895
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
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...
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
4369
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...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2329
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.