Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an <a href="https://stackoverflow.com/a/6390357/1395993">answer</a> that describes the <code>char[1]</code> trick. Basically, the idea is to allocate more memory when <code>malloc()</code>ing the struct, to already have some storage for your string without additional allocation. You can sometimes even see <code>char something[0]</code> used for the same purpose, which makes even less intuitive sense.</p> <blockquote> <p>On the other hand, treating this as a full blown char * doesn't work either, as can be seen with the test_s.b is output above, which should show a NULL pointer then...</p> </blockquote> <p>If something is an array, both its name and <code>&amp;name</code> just give the pointer to the start of the array in C. This works regardless of whether it's a member in a struct, or a free standing variable.</p> <pre><code>printf("real sizeof(test_s.b): %lx \n", ((void *)(&amp;test_s.b) - (void *)(&amp;test_s.a)) ); </code></pre> <p>This line gives the size of space allocated for <strong><code>a</code></strong>, not <code>b</code> in this struct. Put something after <code>b</code> and used this to subtract. With the <code>packed</code> attribute (which means you disallow the compiler to mess with alignment, etc.), you should get 1.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; struct test_struct { char *a; char b[1]; char c; } __attribute__((packed)); int main() { struct test_struct s; printf("%lx\n", ((void*)&amp;s.c) - ((void*)&amp;s.b)); return 0; } </code></pre> <p>I get <code>1</code>.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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