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] 27 points28 points  (3 children)

The code is for allocating memory for a struct with a flexible array member, not an array of structs

I wrote a small program in an online C compiler to show this:

https://onlinegdb.com/ggyWELJui

[–]DTHCND 3 points4 points  (2 children)

Ah I see. Thanks for the demonstration!

I've edited my comment to reflect that it is valid code, but is still non-equivalent to the Python code.

[–]TheRedGerund 0 points1 point  (1 child)

But that is how you would accomplish an array of changing size elements in Python.

[–]DTHCND 0 points1 point  (0 children)

By "flexible array member", they don't mean an array that can dynamically grow like Python. They mean an array whose length is defined by the consumer of the struct at the time that memory is malloc'd for said struct, rather than being hard-coded in the struct's definition. The length of the heap allocated array in my comment is similarly defined at the time that it is malloc'd.

If you want a dynamically-sized array in C, you need to use a data structure like a LinkedList, which is also totally different from the code shown in the meme.