473,725 Members | 2,243 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 2468

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
3478
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
2435
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
5660
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
3179
by: dragoncoder | last post by:
Consider the code class A { private: int a; }; int main(void) { A x; int* ptr = (int*)&x;
33
3656
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
3652
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
4271
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
2648
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
5926
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
2458
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
8752
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
9401
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
9257
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
9116
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
8099
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
6702
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
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
3
2157
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.