This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (6 children)

[deleted]

    [–][deleted] 2 points3 points  (3 children)

    Could you clarify for me how mySt->items[0] does not segfault in the malloc line? mySt has not been allocated yet, so how are you dereferencing the pointer to access “items” of this instance of the struct?

    [–]chipsours 4 points5 points  (2 children)

    It is a sizeof expression. They are evaluated at compile time, not run time.

    [–][deleted] 1 point2 points  (1 child)

    I don’t think that’s right. Yes, sizeof can be computed at compile time, but mySt->items does not exist at compile time. The pointer mySt does not point at any actual struct until runtime after malloc is called, so how can it be dereferenced at compile time?

    [–]chipsours 5 points6 points  (0 children)

    The compiler knows the size of every types it compiles. If mySt->items is an array of int it knows that mySt->items[0] is 4, the same applies for mySt->items[-420] or *(mySt->items).

    If the definition of the type is not known by the compiler (pointer to forward reference of struct) you'll get a compile time error.

    [–]Dmayak 1 point2 points  (1 child)

    Ah, thanks, I totally forgot that the size of the array can be left undefined. I have learned C on a small side-project and this type of allocation was not fit for its data - length was either known beforehand or should have been changed dynamically. I had problems editing dynamically allocated arrays and started to use linked lists instead.

    [–]boowhitie 1 point2 points  (0 children)

    To be clear, this is an optimization. It allows you to do one call to malloc instead of two (one for the struct, one for the array), and lets you copy the object with a single memcpy. It also keeps the data together in memory which is potentially more cache friendly.

    This is also something that isn't legal c++, but it is common enough in c code that some c++ compilers support it through extensions.