473,785 Members | 2,879 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 5715
vi******@gmail. com wrote:
s0s...@gmail.co m wrote:
>vipps...@gmail .com wrote:
>>s0s...@gmail. com wrote:

[about incrementing void pointers as opposed to (char *) cast]

Because sometimes you don't need portability and because
sometimes there's a better way?

Yes, that better way being the portable way, in this case.

Well, it's a matter of whether you prefer void * or char *.

No you idiot, it's a matter of whether you prefer portability
over non-portability without any other gains or loses.
The point being that you can't increment a void* pointer in a
conformant C system. If you (sOs) look at the code generated you
will see that a cast to char* generates none, as does the cast back
to char*. However it clues the compiler in to what is going on.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Sep 18 '08 #131
s0****@gmail.co m wrote:
>
.... snip ...
>
Shouldn't it be unsigned char *? Anyway, my argument was that if
your compiler can perform arithmetic with the void *, then go
void *, as you did above.
Because a compiler can't 'perform arithmetic with the void*'. It
says so, right in the C standard. Trying to do so results in
undefined behaviour.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Sep 18 '08 #132
CBFalconer said:
s0****@gmail.co m wrote:
>>
... snip ...
>>
Shouldn't it be unsigned char *? Anyway, my argument was that if
your compiler can perform arithmetic with the void *, then go
void *, as you did above.

Because a compiler can't 'perform arithmetic with the void*'. It
says so, right in the C standard. Trying to do so results in
undefined behaviour.
Because it's a constraint violation, it also requires the implementation to
issue a diagnostic message. See 3.3.6 of C89 or 6.5.6 of C99.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Sep 18 '08 #133
Nick Keighley wrote:
Richard<rgr...@ gmail.comwrote:
.... snip ...
>
>My pointers were numbers. I could see them in the debugger.

but in general they aren't. Think DOS. Think IBM mainframe.
Are you trying to be dense?
No, he is just re-demonstrating the condition. I have seen many
explanations to him of this elementary fact.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Sep 18 '08 #134
On Sep 17, 5:57*pm, Keith Thompson <ks***@mib.orgw rote:
s0****@gmail.co m writes:
>On Sep 17, 2:24*pm, Eric Sosman <Er*********@su n.comwrote:
[...]
>>* * *1) The function deals with the bytes that represent an object,
* * * * not with the object as such. *I/O functions, memcpy(),
* * * * free(), and so on are type-blind in this sense: They just
* * * * care about the object's bytes, not about its nature.
>Exactly, that's the "bytes" I was referring to. The word "bytes" is
also used to refer to characters. But I was referring to the bytes
that constitute an arbitrary object: int, double, struct, etc., and
that if examined, they will appear to have meaningless values. This is
also why I find it more natural to use void *: you aren't going to
examine what it points to, because all you're going to see are some
arbitrary bits that constitute an object of (possibly) bigger size.

unsigned char is used for both kinds of "bytes".
Sure, because it's the standard way. But I think you can now see why I
find void * more natural for the above kinds of "bytes."

Sebastian

Sep 18 '08 #135
s0****@gmail.co m writes:
On Sep 17, 5:57*pm, Keith Thompson <ks***@mib.orgw rote:
>s0****@gmail.co m writes:
>>On Sep 17, 2:24*pm, Eric Sosman <Er*********@su n.comwrote:
[...]
>>>* * *1) The function deals with the bytes that represent an object,
* * * * not with the object as such. *I/O functions, memcpy(),
* * * * free(), and so on are type-blind in this sense: They just
* * * * care about the object's bytes, not about its nature.
>>Exactly, that's the "bytes" I was referring to. The word "bytes" is
also used to refer to characters. But I was referring to the bytes
that constitute an arbitrary object: int, double, struct, etc., and
that if examined, they will appear to have meaningless values. This is
also why I find it more natural to use void *: you aren't going to
examine what it points to, because all you're going to see are some
arbitrary bits that constitute an object of (possibly) bigger size.

unsigned char is used for both kinds of "bytes".

Sure, because it's the standard way. But I think you can now see why I
find void * more natural for the above kinds of "bytes."
No, I really can't.

If I had the opportunity to go back in time and change C, I'd probably
separate the concepts of "byte" (the fundamental unit of storage) and
"character" . I'd probably make "byte" a keyword and a type name,
referring to a numeric type similar to what we know as unsigned char,
and I'd allow sizeof(char) to be something other than 1. Given such a
change, it would make sense to access raw memory using type byte*, and
you could sensibly perform pointer arithmetic on such a type. I'm not
certain whether void*, a type that points to raw memory but that can't
can't be dereferenced or incremented, would add sufficient value to be
worth having in the language; perhaps memcpy and friends would just
take arguments of type byte*.

But it's *way* too late to make such a change in any language calling
itself "C".

If you want to a raw pointer that can point to any arbitrary object,
use void*. If you want to access the object's representation as bytes
or perform pointer arithmetic, use unsigned char*. If you want to
point to a specific type, or to an array of a specific type, use a
pointer to that type.

You cannot legally perform pointer arithmetic on void* in standard C,
and if you attempt to do so your code will be *gratuitously*
non-portable.

--
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 18 '08 #136
Richard wrote:
Chris Dollin <ch**********@h p.comwrites:
>No, I am not saying that. I'm perfectly happy to believe that your
debugger renders bits of pointer as numbers.

Thats nice. How does your debugger do it?
Probably as numbers. How would I know? It's been so long*.
When you look into memory and you see your pointer stored in an
arry how does it look? Hex number by any chance? What a surprise.
If you cast it to a char * and subtract p
from ++p do you get 4 on a 32 bit machine? I did.....
I've never looked [at this using a debugger]. I've never needed to.
I understand C's computational model for pointers, and I understand
code generation, and I understand how a /particular/ implementation
can represent pointers in the same way it represents numbers, and I
don't confuse this with a /necessary/ property of implementations ,
nor do I confuse scalars and vectors -- a segmented architectures
pointers are multi-component, like vectors, and just because you
can read off a bit-pattern and apply the traditional (but inappropriate)
binary decoding and get a number doesn't mean that bit-pattern
/is/ a number.

--
'It changed the future .. and it changed us.' /Babylon 5/

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

Sep 18 '08 #137
Richard wrote:
The correct statement is

"It is incorrect to increment a non initialised variable since the
behaviour is undefined - however the value may well increment as
expected".
"Or not, at the whim of the implementor. DO NOT RELY ON THIS (if
you expect your code to be even vaguely portable)."

--
'It changed the future .. and it changed us.' /Babylon 5/

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

Sep 18 '08 #138
On 17 Sep, 15:55, s0s...@gmail.co m wrote:
On Sep 17, 3:02*am,Nick Keighley<nick_k eighley_nos...@ hotmail.com>
wrote:
On 16 Sep, 21:14, s0s...@gmail.co m wrote:
>>>You have two options, do it portably, or do it with an extension, with
>>>absolutely no loss in efficiency or size, and you advice to choose the
>>>extension.
>>Well, perhaps the OP doesn't need portability (or at least not this
>>kind of portability).
there is a *well defined* and *portable* way to do this. So why choose
a non-portable way? I'm sorry I've had this sort of argument before
(in my work place) we really are on different planets. Why NOT
use a portable means, if it exists?

Because sometimes you don't need portability and because sometimes
there's a better way?
at the risk of repeating myself. I REALLY do not understand
how anyone can think like this. You wish to do something in C.
You have two options *that produce identical results* and are similar
in programming complexity. One is portable and one is not.

Why not use the portable version?
What is the <expletivepoi nt of using the non-portable version?
What can you possibly gain?

I'll probably give up after this. The trouble with text based
formats is you can't hear how hard I'm hitting my keyboard by
now.

>>Besides, void * seems more natural for this kind
>>of task.
rubbish

Why is it rubbish?
doing arithmatic on a void pointer seems really strange to me.
If you have a void pointer, it will typically point
to any kind of object: int, double, long long, structures, anything.
yup

Does it seem natural to you to treat such an object as if it were a
*character*?
no. It's not a character!

>* * *"This kind of task" was an artificial bit of code specifically
>written to experiment with manipulating pointers. *An investigative
>doodle, nothing more.
No. This "investigat e doodle" demonstrated this kind of task. But this
kind of task is also common in real-world programs, and it's
important. I, for one, have actually done this, without realizing I
was using an extension.
so now you know- so don't do it again

Why not? I'll simply keep in mind that it works only under a certain
compiler.
<nick's head explodes>

--
Nick Keighley

Consistency is the last refuge of the unimaginative.
-- Oscar Wilde
Sep 18 '08 #139
Richard<rg****@ gmail.comwrote:
Chris Dollin <ch**********@h p.comwrites:
No, I am not saying that. I'm perfectly happy to believe that your
debugger renders bits of pointer as numbers.

Thats nice. How does your debugger do it? When you look into memory and
you see your pointer stored in an arry how does it look? Hex number by
any chance? What a surprise.
My dear dunce, if you explicitly ask your debugger to hexdump
everything, _your DNA_ is a hex number. No surprise there, then.
OTOH, if I ask my debugger to do a stringdump of memory, all floating
point numbers will display as strings. Now, is a float therefore a
string?

Richard
Sep 18 '08 #140

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
2130
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
1853
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
1564
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
2328
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
2646
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
1825
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
9480
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
10329
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
10152
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
10092
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
8974
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
7500
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
5381
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2880
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.