I understand how to create a struct
on the heap using malloc
. Was looking for some documentation regarding creating a struct
in C on the stack but all docs. seem to talk about struct creation on heap only.
Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.
Most importantly, a struct unlike a class, is a value type. So, while instances of a class are stored in the heap, instances of a struct are stored in the stack. When an instance of a struct is passed to a method, it is always passed by value.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ }; Here tag_name is optional in some contexts.
Structs are like int s. If you have a local int , it will generally be on the stack, if you have a list of int s, they are stored directly in the list's internal array, which is on the heap.
The same way you declare any variable on the stack:
struct my_struct {...}; int main(int argc, char **argv) { struct my_struct my_variable; // Declare struct on stack . . . }
To declare a struct on the stack simply declare it as a normal / non-pointer value
typedef struct { int field1; int field2; } C; void foo() { C local; local.field1 = 42; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With