Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove constness of a pointer in a struct in C
    primarykey
    data
    text
    <p>So I need to remove constness from some variables in C (I know what I'm doing). So I wrote a little macro (<code>UNCONST</code>) which lets me assign an new value to a const value. This works just fine for normal variables of types like <code>int</code>. But this doesn't work for pointers. So I can't let a pointer point to a different position using my macro <code>UNCONST</code> without getting an compiler warning.</p> <p>Here a little test program <code>unconst.c</code>:</p> <pre><code>#include &lt;stdio.h&gt; #define UNCONST(type, var, assign) do { \ type* ptr = (type*)&amp;(var); \ *ptr = (assign); \ } while(0) struct mystruct { int value; char *buffer; }; int main() { // this works just fine when we have an int const struct mystruct structure; UNCONST(int, structure.value, 6); printf("structure.value = %i\n", structure.value); // but it doesn't when we have an char * char *string = "string"; UNCONST(char *, structure.buffer, string); printf("structure.buffer = %s\n", structure.buffer); // this doesn't work either, because whole struct is const, not the pointer. structure.buffer = string; printf("structure.buffer = %s\n", structure.buffer); } </code></pre> <p>compiling &amp; executing</p> <pre><code>$ LANG=en gcc -o unconst unconst.c unconst.c: In function ‘main’: unconst.c:21:3: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default] unconst.c:25:3: error: assignment of member ‘buffer’ in read-only object </code></pre> <p>Is there a way to optimize my macro so this warning doesn't show up?</p>
    singulars
    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