473,770 Members | 6,978 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about void pointers

Is this valid?

int a[20];
void *b;

b = (void *)a; // b points to a[0]

b += 5*sizeof(*a); // b points to a[5]

a[5] = 100;

printf( "%d\n" , *((int *)b) ); // prints 100

If so, if a had been a struct, would it still work?

Is there a possibility that the array could contain some padding, so
rather than sizeof, the assignment would be

b += 5*( (void *)(&(a[1])) - (void *)(&(a[0]));

which seems more more complex.

Would any padding be incorporated into sizeof anyway?
Sep 16 '08
160 5704
Richard<rg****@ gmail.comwrites :
Ben Bacarisse <be********@bsb .me.ukwrites:
>Richard<rg**** @gmail.comwrite s:
>>vi******@gmail. com writes:

On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
when you do
--char *c; c++; ==c is incremented by 1
--long int *x; x++ ==x is incremented by 4.

Wrong, assuming x was initialized, it would be incremented by 1.

Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.
Why? I honestly can't see why you think it must do anything at all.

The whole point of my post was to say "beware" to people who
mock undefined behaviour because you don't know the future. On the
Cambridge CAP machine, that code would terminate the program before
the increment. In fact, 'int *x; x;' could terminate the program if the
compiler did not optimise the reference to x away. Do you know that
the code will increment on every future machine, now that this awkward
old one is so much scrap?

--
Ben.
Sep 17 '08 #61
Richard Heathfield <rj*@see.sig.in validwrites:
Keith Thompson said:
[...]
>Wrong.

Well, obviously. Look at the source.

Nevertheless, incredible as it may seem, some people might not realise even
now that the source is unreliable, so here's C&V from both Standards (the
wording is identical in each):

C89, 3.1.2.5, and C99, 6.2.5(26): "A pointer to void shall have the same
representation and alignment requirements as a pointer to a character
type."
This originated with an attempt by one of the trolls to refute a
statement that CBFalconer never actually made, in contrast to the
perfectly correct statement that he did make.

The language requires void* and char* to have the same
representation, but it does not allow pointer arithmetic on void*
(Chuck made the latter statement). More precisely, any attempt
to perform such arithmetic is a constraint violation, requiring
a diagnostic.

The whole point of having void* in the language is that it
doesn't point to any specific type. Allowing arithmetic on
void* as an extension, as if it pointed to a one-byte object,
weakens that distinction for the sake of some minor convenience.
(A side effect of the way this extension is implemented is that,
absurdly, sizeof(void)==1 .)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 17 '08 #62
Ben Bacarisse <be********@bsb .me.ukwrites:
Richard<rg****@ gmail.comwrites :
>Ben Bacarisse <be********@bsb .me.ukwrites:
>>Richard<rg*** *@gmail.comwrit es:

vi******@gmail. com writes:

On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
>when you do
>--char *c; c++; ==c is incremented by 1
>--long int *x; x++ ==x is incremented by 4.
>
Wrong, assuming x was initialized, it would be incremented by 1.

Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.

Why? I honestly can't see why you think it must do anything at all.
I dont think it *must* do anything at all. But I am yet to see a machine
where it is not incremented if it is not initialised. Its
"uninitiali sed" value is incremented in each and every case. Sure its
"undefined behaviour in terms of the value, but its still UDV+1 ...
>
The whole point of my post was to say "beware" to people who
mock undefined behaviour because you don't know the future. On the
Let me make something very clear - I am not mocking UDB. I am just
pointing out that in most cases it is WRONG to say the unitialised
variable is NOT incremented. It is. In nearly all cases and certainly in
EVERY case I have worked on on various common machines.
Cambridge CAP machine, that code would terminate the program before
the increment. In fact, 'int *x; x;' could terminate the program if the
compiler did not optimise the reference to x away. Do you know that
the code will increment on every future machine, now that this awkward
old one is so much scrap?

--
Sep 17 '08 #63
s0****@gmail.co m wrote:
On Sep 16, 11:51 am, ra*****@gmail.c om wrote:
>On Sep 16, 4:20 pm, vipps...@gmail. com wrote:
>>b = ((unsigned char *)b) + 5 * sizeof *a;
I see, got to switch to char * so that it can be incremented properly.

No, to unsigned char *. But if your compiler can do it with the void
*, then do it with the void *. It's probably specialized for that kind
of stuff anyway.
There's two things wrong with what you said:
1 It doesn't matter whether the cast is to
(char *) or (unsigned char *),
because the pointer arithmetic is the same.
2 (void *) is wrong. You shouldn't write code that only works
on your compiler, without a special reason.
There is no special reason here.

--
pete
Sep 17 '08 #64
Richard<rg****@ gmail.comwrites :
Ben Bacarisse <be********@bsb .me.ukwrites:
>Richard<rg**** @gmail.comwrite s:
>>vi******@gmail. com writes:
On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
when you do
--char *c; c++; ==c is incremented by 1
--long int *x; x++ ==x is incremented by 4.

Wrong, assuming x was initialized, it would be incremented by 1.

Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.
And who exactly said "it will not increment"?

vippstar's actual statement, which you quoted, was:

"... assuming x was initialized, it would be incremented by 1".

He quite reasonably chose not to make any claim about what would
happen if x was not initialized.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 17 '08 #65
Keith Thompson <ks***@mib.orgw rites:
Richard<rg****@ gmail.comwrites :
>Ben Bacarisse <be********@bsb .me.ukwrites:
>>Richard<rg*** *@gmail.comwrit es:
vi******@gmail. com writes:
On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
>when you do
>--char *c; c++; ==c is incremented by 1
>--long int *x; x++ ==x is incremented by 4.
>
Wrong, assuming x was initialized, it would be incremented by 1.

Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.

And who exactly said "it will not increment"?

vippstar's actual statement, which you quoted, was:

"... assuming x was initialized, it would be incremented by 1".

He quite reasonably chose not to make any claim about what would
happen if x was not initialized.
Can you be more obstinate and childish? There is nothing "reasonable "
about it all in the context of which I am talking. In the greater
majority of cases x will incremented REGARDLESS of whether it was
initialised or not. Why this is so tricky for you to understand I am not
sure. You seem unable to think outside of the standard. Do try.

Yes, yes demons out of noses etc etc. But meanwhile in the real world.
And ONCE AGAIN : yes I DO understand that incrementing an uninitialised
variable is a silly thing to do.
Sep 17 '08 #66
Richard<rg****@ gmail.comwrites :
Ben Bacarisse <be********@bsb .me.ukwrites:
>Richard<rg**** @gmail.comwrite s:
>>Ben Bacarisse <be********@bsb .me.ukwrites:

Richard<rg** **@gmail.comwri tes:

vi******@gmail. com writes:
>
>On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
>>when you do
>>--char *c; c++; ==c is incremented by 1
>>--long int *x; x++ ==x is incremented by 4.
>>
>Wrong, assuming x was initialized, it would be incremented by 1.
>
Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.

Why? I honestly can't see why you think it must do anything at all.

I dont think it *must* do anything at all.
Good. We are agreed. I can't see how your "even if it wasn't
initialised it would be incremented by something" is consistent with
that because it suggests at least one thing must happen -- some form
of increment -- but it seems you don't hold that view any more.
But I am yet to see a machine
where it is not incremented if it is not initialised. Its
"uninitiali sed" value is incremented in each and every case. Sure its
"undefined behaviour in terms of the value, but its still UDV+1 ...
Ah, you do it seems. That is not what the standard says. It says
that the value may be a trap representation and that accessing such a
thing in the normal way is undefined. At that point (which can be
before the increment) the program may terminate or do whatever your
favourite example of UB is. I think termination is undefined enough
and is what the machine I described would do.
>The whole point of my post was to say "beware" to people who
mock undefined behaviour because you don't know the future. On the

Let me make something very clear - I am not mocking UDB. I am just
pointing out that in most cases it is WRONG to say the unitialised
variable is NOT incremented.
I did not say it is *not* incremented -- you said it *will* be and at
the time you gave no exceptions.

The standard says it may not be and think you have missed that
possibility. Pointers can be invalid in such a way that merely
"touching" them cause a fault. This is an excellent bit of standards
writing and allows C to be implemented on machines with very strict
address checking in hardware (such as the CAP).
It is. In nearly all cases and certainly in
EVERY case I have worked on on various common machines.
I would never have posted if you had said "even uninitialised, it will
usually be incremented". You agree the undefined behaviour is
important but rather than point out that the example has undefined
behaviour you just chose to say what usually happens on current
machines. That does not add to the general readers stock of
understanding.

--
Ben.
Sep 17 '08 #67
Peter Nilsson <ai***@acay.com .auwrites:
CBFalconer <cbfalco...@yah oo.comwrote:
>Peter Nilsson wrote:
Keith Thompson <ks...@mib.orgw rote:
... why does printf have a "%p" format?

That's actually a very good question! If you ever hear
a good answer, please share it.

Well, how about "to allow printf to output a printable char
representati on of a void* pointer,

How often is this useful? When it is, how useful is %p?
Printing pointer values probably useful very often, but I like having
"%p" for those cases where it is useful.
>readable by scanf to reconstitute that pointer".

Having printed a pointer with %p, how does a program guarantee
that subsequent printed characters will not undermine scanf's
ability to reconstitute a comprable pointer value?
I must admit I've used *printf and *scanf to print and reconstitute a
pointer value. But with reasonable precautions, such as printing the
value at the end of a line with something recognizable in front of it,
I wouldn't have any qualms about assuming that the output format will
be reasonable. A new-line character in the middle of the result would
mess this up, but I'm content to count on vendors not to do something
that silly.
If I do something like...

printf("ptr is %p\n", (void *) ptr);

...what is the guarantee that the output won't exceed an
implementation' s limit on text line width?
There's no actual guarantee of this, but again, I'm willing to assume
reasonable behavior. Having the output of "%p" exceed the maximum
text line length is hardly the only silly but legal thing a perverse
implementation could do.
When I do print pointers, I hex dump the representation.
It's the only way to gain full control over the output.

#include <stdio.h>
#include <limits.h>

#define CHAR_NIBBLE ((CHAR_BIT + 3) / 4)

void dump_ptr(FILE *fp, const void *ptr)
{
const unsigned char *p = (const unsigned char *) &ptr;
size_t i;
for (i = 0; i < sizeof ptr; i++)
fprintf(fp, "%0*X", CHAR_NIBBLE, (unsigned) *p++);
}
Sure, that works too. On the other hand, on some systems it's
traditional to show addresses in octal rather than in hexadecimal; on
others, address might be segmented, and your method loses the
distinction between the discrete pieces of the address, something that
"%p" would probably capture.

And it prints the bytes backwards on a little-endian system.

Also, if two different representations represent the same address
(possible in a segmented addressing system), "%p" could at least
potentially normalize them.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 17 '08 #68
Richard<rg****@ gmail.comwrites :
Keith Thompson <ks***@mib.orgw rites:
>Richard<rg**** @gmail.comwrite s:
>>Ben Bacarisse <be********@bsb .me.ukwrites:
Richard<rg** **@gmail.comwri tes:
vi******@gmail. com writes:
>On Sep 16, 7:13 pm, sh.vi...@gmail. com wrote:
>>when you do
>>--char *c; c++; ==c is incremented by 1
>>--long int *x; x++ ==x is incremented by 4.
>>
>Wrong, assuming x was initialized, it would be incremented by 1.
>
Even if it wasnt initialised it would be incremented by something.

This thread has gone off in another direction, but I want to come back
to this. Please, coders of the world, don't take this remark from
Richard to heart -- think of your children!

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.

And who exactly said "it will not increment"?

vippstar's actual statement, which you quoted, was:

"... assuming x was initialized, it would be incremented by 1".

He quite reasonably chose not to make any claim about what would
happen if x was not initialized.

Can you be more obstinate and childish? There is nothing "reasonable "
about it all in the context of which I am talking. In the greater
majority of cases x will incremented REGARDLESS of whether it was
initialised or not. Why this is so tricky for you to understand I am not
sure. You seem unable to think outside of the standard. Do try.
You know what? This most recent statement of yours:

In the greater majority of cases x will incremented REGARDLESS of
whether it was initialised or not.

is one that I agree with.

So what's your problem?

Read the quoted material above. vippstar made a perfectly correct
statement, that x will be incremented if it's been initialized
(leaving aside for the moment the question of whether it's incremented
by 1 or by 4). Expanding that statement to cover the case where x has
not been initialized would have required, for accuracy, a discussion
of undefined behavior, trap representations , and all that stuff. He
quite reasonably chose not to open that can of worms.

You responded by claiming, without qualification, that x will be
incremented even it hasn't been initialized. You've now backed off
from that statement with your "greater majority of cases"
qualification, but you refuse to acknowledge that your more recent
statement differs from your earlier one.
Yes, yes demons out of noses etc etc. But meanwhile in the real world.
And ONCE AGAIN : yes I DO understand that incrementing an uninitialised
variable is a silly thing to do.
I'm glad to hear it -- and a bit surprised, given that many of your
earlier statements in this thread did not demonstrate such knowledge.

Please try to understand that your earlier claim that:

Even if it wasnt initialised it would be incremented by something.

could easily mislead an unwary newbie into thinking that it's safe to
increment an uninitialized pointer.

In addition, your later statement:

Oh for goodness sake Ben, I was not condoning it! But to say "it will
not increment" is clearly false.

is correct, but it could lead someone to the incorrect conclusion that
someone had actually written "it will not increment".

You might think that putting words into other people's mouths makes it
easy to win arguments, but that trick doesn't work so well when
people's actual words are recorded.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 17 '08 #69
On Tue, 16 Sep 2008 09:51:22 -0700 (PDT), ra*****@gmail.c om wrote:
>On Sep 16, 4:20 pm, vipps...@gmail. com wrote:
>b = ((unsigned char *)b) + 5 * sizeof *a;

I see, got to switch to char * so that it can be incremented properly.
If you cast b to int* then the expression could be simpler:
b = ((int *)b) + 5;

Any pointer to a complete type can be used for pointer arithmetic.
>
>Yes, but by using the offsetof() macro in <stddef.h>

I meant to point to the structure.

struct st { int val; } a[100];

void *b;

a[5].val = 100;

b = a;
b = ((unsigned char *)b) + 5 * sizeof *a;

printf( "%d\n" , b->val );
Why don't you just run it through your compiler and note the mandatory
diagnostic? The left operand of -must be a pointer to struct. While
b has the correct value, does it have the correct type?

--
Remove del for email
Sep 17 '08 #70

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

Similar topics

11
2577
by: kazack | last post by:
I am under the the impression that a variable is what is stored in a memory address and a pointer is the memory address of the variable? I was looking to use a function that does not return a value void whatever(whatever) and not have a variable global but in main and change the value in the void whatever function. using namespace std; void whatever(int);
18
2129
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for last_values as well as assign the value of a pointer to the assigned space. Which I think I'm doing by using:
14
1347
by: streamkid | last post by:
i'm a learning newbie at c++... and i have the following question... reading some source code, i saw this: int function(const void * one, const void * two) { int var1, var2; var1 = *((int*)one); var2 = *((int*)two); /* sm other code here*/ }
21
1851
by: Bo Yang | last post by:
As long as I write c++ code, I am worry about the pointer. The more the system is, the dangerous the pointer is I think. I must pass pointers erverywhere, and is there a way to ensure that every object pointered by any pointer will be deleted and only be deleted once?
4
1860
by: Jeffrey Spoon | last post by:
Hello, I am trying to make a simple function that returns a pointer to another function. In my header file I've declared my function pointer: void (*pStateFunction) (void); //assume the function pointed to returns void and the actual function that returns the pointer: void* getState(CString myString);
10
1719
by: Zero | last post by:
Hello all, I wonder about void? To which category in the C programming language does it belong? Of how many bits consits void? Is it possible to define a varibale called void a;
21
1563
by: Chad | last post by:
At the following url http://c-faq.com/lib/qsort2.html, they have the following Q: Now I'm trying to sort an array of structures with qsort. My comparison function takes pointers to structures, but the compiler complains that the function is of the wrong type for qsort. How can I cast the function pointer to shut off the warning? A: The conversions must be in the comparison function, which must be declared as accepting ``generic...
17
2326
by: Ben Bacarisse | last post by:
candide <toto@free.frwrites: These two statements are very different. The first one is just wrong and I am pretty sure you did not mean to suggest that. There is no object in C that is the same as its address. The second one simply depends on a term that is not well-defined. Most people consider the type to be an important part of the notion of
18
2645
by: mdh | last post by:
May I ask the following. By K&R's own admission, the example used to describe function pointers is complex ( on P119). In addition, the use of casts has been stated by some on this group as being, again, a poor/bad example of it's use. For the moment, accepting these criticisms, I would still like to get some insight into why/how some things work as even poor code is enlightening, to me at least. The example uses K&R's version of...
28
1824
by: junky_fellow | last post by:
Guys, Consider a function func(void **var) { /* In function I need to typecast the variable var as (int **) I mean to say, I need to access var as (int **) }
0
9591
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
9425
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
10228
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
10057
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
9869
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
6676
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
5312
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
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3575
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.