Afficher un message
Vieux 11/04/2008, 16h59   #3
Ben Bacarisse
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Storing integer values in a void*

lithiumcat@gmail.com writes:

> I'm using some functions to store and retrieve data as a void*.

<snip>
> But I want to use that code to store small integers (maybe not more
> than a thousand, but I don't want to hardcode a limit)

<snip cast void * to int method>
> However I'm not sure any standard guarantees this to work,


No, you are right. It is not guaranteed to work. It will work in
lots of cases, but it is not portable.

> so I was
> looking for a more portable solution. I thought doing some pointer
> arithmetics :
> /* global variable to be used for base of pointers */
> char base;
> /* storage */
> int i = value_to_be_stored;
> char *data = &base + i;
> store_data_as_voir_ptr(data);
> /* retrieval */
> int i;
> char *data = get_data_returned_as_void_ptr();
> i = data - &base;
> /* use i */
>
> But is this really portable (assuming i is small enough so there is no
> overflow) ? I guess the pointers will probably be invalid, but as they
> are never dereferenced, it is alright, isn't it ?


Clever but, no, not portable. Even constructing an address outside of
and object (except for the off-by-one-at-the-end permission) is
undefined.

The only portable solution that I can think of is the union idea
already posted. This, of course, requires changes to the AVL tree
code, so it may not be an option.

--
Ben.
  Réponse avec citation
 
Page generated in 0,05469 seconds with 9 queries