Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 354
stressed_geek Avatar asked Jun 06 '12 14:06

stressed_geek


People also ask

Can structs be on the stack?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Why struct is stored on the stack?

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.

How do you declare a struct in C?

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.

Is struct a stack or heap?

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.


2 Answers

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     .     .     . } 
like image 162
harald Avatar answered Oct 02 '22 18:10

harald


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; } 
like image 31
JaredPar Avatar answered Oct 02 '22 17:10

JaredPar