473,623 Members | 3,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer conversions and Data types conversions

vb
Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so?

Nov 15 '05 #1
10 2211
vb@gmail.com wrote:

Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so?


No.
A pointer can be converted to a pointer to void,
and converted back to the original type and value.
Little else is guaranteed about conversions to pointer to void.

--
pete
Nov 15 '05 #2

vb@gmail.com wrote:
Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so?

Every pointer is an address of memory.Most of the pointers are integers
and a few are not (This has been mentioned in comp.lang.c.).T he kind of
pointer will tell the compiler how many bytes and what type of the data
it points to.So we can cast a pointer from one type to another,but it
is not safe and maybe you get some warnings!You should be careful
enough to use a 'void*' pointer,though it is very useful.

Nov 15 '05 #3
vb@gmail.com wrote:
Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer
Casts are explicit conversions, and actually a side-issue here. What you are
really talking about is conversions in general, not necessarily explicit
conversions.

In fact, the guarantee in the Standard amounts to this: that, for any object
type T, the following transformation:

T *tp = &SomeObjectOrOt herOfTypeT;
void *vp = tp;
T *ntp = vp;

does not lose information. That is, after this code is executed, tp and ntp
will point to the same object.

If you are silly enough to do this:

T *tp = &SomeTOrOthe r;
void *vp = tp;
U *up = vp;

then you are skating on much thinner ice. For example, pointers-to-T and
pointers-to-U might have different numbers of significant bits.

so this implies that any pointer can be
cast to any other pointer. Is that so?


Yes, there is no limit to the thinness of the ice on which you can skate.
Sooner or later, though, the surface will crack, and in you'll go. Wise men
observe the signs, rather than take the dunking.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
mail: rjh at above domain
Nov 15 '05 #4
Cong Wang wrote:

So we can cast a pointer from one type to another,but it
is not safe and maybe you get some warnings!


Unfortunately, the cast is more likely to /remove/ some warnings, which is
why many people are silly enough to use it so often.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
mail: rjh at above domain
Nov 15 '05 #5
pete <pf*****@mindsp ring.com> wrote:
vb@gmail.com wrote:

I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so?


No.
A pointer can be converted to a pointer to void,
and converted back to the original type and value.
Little else is guaranteed about conversions to pointer to void.


This is true for object pointers (and pointers to incomplete types), not
for function pointers.

Pointers to types not qualified const etc. may be converted to pointers
to that same type with such qualifiers, and the result is a usable
pointer to the same object or function as the original.
Null pointer constants may be converted to any pointer type, and will
result in a null pointer; and null pointers may be converted to any
other kind of null pointer.
Integers may be converted to pointers, but not usefully unless your
implementation specifies this beyond the Standard (some do). Ditto vice
versa, and if the result can't be represented in the target type, you
have outright UB.
Object and incomplete-type pointers may be converted to one another, but
not usefully (the result is not required to be well-aligned, and if not,
the result is UB), except for:
Object pointers may be converted to pointer to (any kind of) char, and
the result points at the first byte of the object pointed to.
Function pointers may be converted to any function pointer type, and
remain their original value; you cannot reliably call a function through
a pointer of the wrong type, but you can convert it back to the right
type and get a callable pointer.

Richard
Nov 15 '05 #6
Never do such things in real code. you will do a segfault in 90% of
cases.

Nov 15 '05 #7
On Mon, 01 Aug 2005 01:02:22 -0700, Cong Wang wrote:

vb@gmail.com wrote:
Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so? Every pointer is an address of memory.


Not necessarily. For example a null pointer need not in any sense
correspond to a memory address.
Most of the pointers are integers
and a few are not (This has been mentioned in comp.lang.c.).
There is no sense in which C considers a pointer to be an integer. C does
allow casting between pointer and integer types but the language doesn't
define the result in most cases, except that a null pointer constant
(which may be an integer) converted to a pointer type gives a null
pointer. Thinking of pointers as integers isn't really useful and can
lead to dangerous/wrong assumptions.
The kind of
pointer will tell the compiler how many bytes and what type of the data
it points to.
A pointer to object type indicates the size of object being pointed at, a
pointer to incomplete type (e.g. void *, pointer to an incomplete
structure, union or array typeor a pointer to a function doesn't.
So we can cast a pointer from one type to another,but it
is not safe and maybe you get some warnings!You should be careful
enough to use a 'void*' pointer,though it is very useful.


Casts very often get rid of warnings which is what makes them so
dangerous. Just because the compiler doesn't warn doesn't mean the code is
correct or even well defined.

Lawrence
Nov 15 '05 #8
In article <11************ **********@o13g 2000cwo.googleg roups.com>
vb@gmail.com <vb*****@gmail. com> wrote:
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to me, since any pointer can be cast to void* and void * can
be cast to any other pointer so this implies that any pointer can be
cast to any other pointer. Is that so?


As others have noted, it is not so. The reasoning here has a
flaw.

You are correct in that any "data pointer" (but not function pointer)
can be converted to "void *" and back without losing any important
information. But from this, you conclude that any (data) pointer
can be converted to any other data pointer. Why?

Consider, if you will, "int" and "double" as a similar example.
Suppose that "int" ranges from -32768 to +32767 (as it does on most
16-bit CPUs) or even -2147483648 to +2147483647 (as it does on most
32-bit CPUs), while "double" is a typical 8-byte IEEE double that
has 53 "mantissa" bits and thus can represent all integers up to
+/- 900719925474099 2 (remember that IEEE floating point uses
sign-and-magnitude representation, so unlike two's complement,
the range is symmetric).

Now imagine that "double" is analagous to both "void *" and
"char *" ("byte pointers"), while "int" is the analagous to
"int *" and other "word pointers". You can always take any
word pointer and store it in a byte pointer, just as you can
always take an ordinary "int" value and store it in a "double".
But there are "double" values that you cannot store in an
"int", such as 3.5. If you store 3.5 in an int, the 0.5
part "falls off the end", and when you convert it back to
double, you get 3.0.

The same actually happens (on some real machines) when you use byte
pointers and word pointers. Word pointers only ever point to "whole
words": word 0, word 1, word 2, and so on. But each "whole word"
is made up of at least 2 (and as many as 8, on the Cray) "bytes"
-- so a byte pointer needs one, two, or even three more bits than
a word pointer. When you convert from one to the other, the extra
bits are added or removed as needed. If the bits in a byte pointer
were not zero, removing those bits discards "useful information",
and when you convert the word pointer back to a byte pointer, the
byte offset within the word is gone: the pointer's value has changed.

Less concretely (but perhaps easier to remember): Think of pointer
values as water, and pointer objects (of various types, like
"int *" and "struct foo *") as cups, glasses, mugs, beer-steins,
and the like. "void *" is a Really Big Bucket, into which you can
pour *any* container of pointer. You can then pour the contents
back into the original container, because the Big Bucket will only
be as full as the original container was. But if you pour a beer
stein ("char *") into the bucket ("void *"), then pour the bucket
into a shot-glass ("int *"), some of the beer will slop out.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '05 #9
as*********@gma il.com writes:
Never do such things in real code. you will do a segfault in 90% of
cases.


Context, dammit!

If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #10

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

Similar topics

35
2880
by: tuko | last post by:
Hello kind people. Can someone explain please the following code? /* Create Storage Space For The Texture */ AUX_RGBImageRec *TextureImage; /* Line 1*/ /* Set The Pointer To NULL */ memset(TextureImage,0,sizeof(void *)*1); /* Line 2*/ According to my knowledge in the first line
23
2716
by: Leon Brodskiy | last post by:
Hi, Could please anyone clarify about pointer and array in C? If I have: int arr; The following two commands will be the same: arr and &arr.
16
2289
by: junky_fellow | last post by:
According to Section A6.6 Pointers and Integers (k & R) " A pointer to one type may be converted to a pointer to another type. The resulting pointer may cause addressing exceptions if the subject pointer does not refer to an object suitably aligned in storage. It is guaranteed that a pointer to an object may be converted to a pointer to an object whose type requires less or equally strict storage alignment and back again without change;...
204
12981
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
41
10015
by: Alexei A. Frounze | last post by:
Seems like, to make sure that a pointer doesn't point to an object/function, NULL (or simply 0) is good enough for both kind of pointers, data pointers and function pointers as per 6.3.2.3: 3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed...
8
2224
by: Martin Jørgensen | last post by:
Hi, "C primer plus" p.382: Suppose we have this declaration: int (*pa); int ar1; int ar2; int **p2;
11
7929
by: quakewang | last post by:
hi, I have define in a head file like this: #define GLUT_BITMAP_9_BY_15 ((void*)2) #define GLUT_BITMAP_8_BY_13 ((void*)3) #define GLUT_BITMAP_TIMES_ROMAN_10 ((void*)4) #define GLUT_BITMAP_TIMES_ROMAN_24 ((void*)5) then I use the constan in switch, like: switch(font) {
5
3889
by: jason.cipriani | last post by:
There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s static_cast<>? In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; // <--- this
12
3283
by: lithiumcat | last post by:
Hi, I bothered you a while back about storing integer values in void*. Now in a completely unrelated context, I'm trying to store pointer values in an integer type. So the basic question is, is it possible to convert a pointer into an integer, and then later (but on the same execution environment, ie the program has not exited, thus it's the same architecture, same compiler, same binary representations and so on) retrieve from the
0
8162
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
8662
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
8603
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
8463
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
5560
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
4067
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
4154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1769
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1468
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.