In C and C++, arrays can be stored in different areas of memory depending on
their storage class and whether they are defined inside or outside a function.
If an array has automatic storage class (also known as local variables), it is
stored on the stack. The stack is a portion of memory used for storing local
variables and function call data. When a function is called, the arguments and
local variables of the function are pushed onto the stack. When the function
returns, the data is popped off the stack. Automatic variables are created when
the function is called and destroyed when the function returns.
Here's an example of an array with automatic storage class:
Copy code
void func() {
// Declare an automatic array
int arr[10];
}
In this example, the array arr is stored on the stack.
If an array has static storage class, it is stored in the static data area of
memory. The static data area is a portion of memory used for storing global
variables and static local variables. Variables with static storage class retain
their values between function calls and are initialized to zero when the program
begins execution.
Here's an example of a static array:
Copy code
// Declare a static array
static int arr[10];
In this example, the array arr is stored in the static data area.
If an array has extern storage class, it is stored in the static data area
of memory along with other global variables. Extern variables are defined in one
source file and can be used in other source files by using the extern keyword.
These variables are visible throughout the program and are initialized to zero
when the program begins execution.
Here's an example of an extern array:
Copy code
// Declare an extern array in one source file
extern int arr[10];
// Use the extern array in another source file
extern int arr[10];
In this example, the array arr is stored in the static data area along with other
global variables.
It's important to note that arrays with automatic storage class and static
storage class are stored in different areas of memory and have different lifetimes.
Automatic variables are created when a function is called and destroyed when the
function returns, while static variables retain their values between function calls
and are initialized to zero when the program begins execution.
int main()
{
// All these variables get memory
// allocated on stack
int a;
int b[10];
int n = 20;
int c[n];
}
To embed this program on your website, copy the following code and paste it into your website's HTML: