If you have a struct in C like this:
struct mystruct{
int i;
char c;
};
and you do:
mystruct m;
m.i = 5;
m.c = 'i';
do you create the struct on the heap or on the stack ?
In the stack:
void func()
{
mystruct m;
...
}
// The address of 'm' is within the stack memory space
In the heap:
void func()
{
mystruct* m = malloc(sizeof(mystruct));
...
}
// The value of 'm' is an address within the heap memory space
In the data-section:
mystruct m;
static mystruct m;
void func()
{
static mystruct m;
...
}
// The address of 'm' is within the data-section memory space
In the code-section:
const mystruct m;
const static mystruct m;
void func()
{
const mystruct m;
...
}
void func()
{
const static mystruct m;
...
}
// The address of 'm' is within the code-section memory space
UPDATE:
Although not directly related to your question, please note that the above rule for const is not entirely accurate, as this keyword has in fact two purposes:
But feature #1 is really up to the compiler in use, which may place it elsewhere, depending on your project configuration. For example, sometimes you might want to declare a constant variable just for the sake of feature #2, while feature #1 is not feasible due to insufficient memory space in the code-section.
const won't generally affect where the variables live. Take something like void func(char * p) { const char * cp = p; }, where cp will be - and would have to be - created on the stack like any other local variable.cp will point to an address on the stack, it will be placed in the code-section (i.e., the address of cp will be an address in the code-section).sizeof, even if you don't like the sizeof(mystruct) style.cp, and the compiler cannot possibly know how many times it will be called.sizeof, and I fixed it as soon as I noticed it was edited by someone else.The stack. You have to use malloc/calloc to create a heap variable.
struct mystruct m;.