Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring small data in a pointer in C?
    primarykey
    data
    text
    <p>To keep this simple, I have a struct along the lines of</p> <pre><code>typedef struct foo { void *data; size_t sz; /* various other crap */ } foo_t; </code></pre> <p>but I'm finding about 90% of the time it really just needs to store a byte or at most a short (but, sometimes, it needs to be a big section of memory). Am I asking for a headache to wrap gets and sets with functions that do some sort of size checking and just store and read the small data directly in data rather than using it as a pointer? The logic seems pretty simple, e.g.</p> <pre><code>if (f-&gt;sz &lt;= sizeof(void*) &amp;&amp; f-&gt;sz == sizeof(char)) { return (char) f-&gt;data; } </code></pre> <p>The advisability of this from a maintenance perspective aside (on the one hand, it makes freeing 90% of the structs much easier and doesn't allocate tons of single chars God knows where on the heap; on the other hand, it means every read and write now has multiple code paths it might take, meaning I'll hate this at some point in the future), is there any particular reason I <i>can't</i> just store a char (or anything else not larger than sizeof(void*)) in a pointer and read it back later? Am I going to hit endian problems or whatever on weird platforms? I remember way back a CS prof saying "it's wrong to say 'pointers are integers'; integers are one way of implementing pointers" but I don't know if he was just making a conceptual point, or if there are real problems with storing non-address data in a spot the compiler has been told is a pointer.</p> <p>(I mean, obviously if I then mistakenly <i>use</i> one of those as a pointer, that's going to cause pain, but I'm too smart to ever do that... right?...)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload