How to create a struct on the stack in C?
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.
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;
}