How can you dynamically allocate memory using stack ( not heap )?
Do they need different functions than malloc(),calloc() ? Which header file is used?
alloca(3) is the function you're looking for.
void test_alloca(int num)
{
int *myarray = alloca(num * sizeof(int));
// do not try to free(myarray) !
}
In C99 you can also declare a variable-length array:
void test_vla(int num)
{
int myarray[num];
}
These two code snippets are functionally identical. (An exception being that the first declares a pointer while the second declares an array, leading to different results if you take the sizeof(myarray).)
The sentence in your question
dynamically allocate memory using stack
is a bit broad. However, In my opinion, you have two options,
But remember the fundamental difference, the lifetime of the allocated memory through aforesaid process will be limited by their scope.