Preface:
Every time you build (compile and link) your project, an executable image is created, divided into three sections:
Code-Section
Data-Section
Stack
Now will relate to four different scenarios:
Scenario #1 - a local array (declared inside a function):
int func()
{
char array[]="string";
...
}
After you load and run the program, every time the function is called, 7 bytes located somewhere on the stack are initialized with the following values: 's', 't', 'r', 'i', 'n', 'g', 0. The address on the stack where these bytes are located, is the value of the SP register when the function is called. Hence, each time the function is called, these 7 bytes may reside in a different address in memory.
Scenario #2 - a global array (declared outside a function):
char array[]="string";
During compilation (before you load and run the program), 7 bytes in the data-section are set with the following values: 's', 't', 'r', 'i', 'n', 'g', 0. These bytes are "hard-coded" into the executable image, and once it is loaded into memory (i.e., whenever you run the program), they reside in the same address throughout the execution of the program.
Scenario #3 - a pointer to a local array (declared inside a function):
int func()
{
char* array="string";
...
}
Same as scenario #2, except for the fact that these 7 bytes are located in the code-section (which is a read-only section), instead of in the data-section (which is a read/write section). In addition, a pointer (array
) is allocated on the stack and initialized (set to point to the address of "string"
in the code-section) every time the function is called. The size of this pointer is typically 4 bytes when using 32-bit RAM, or 8 bytes when using 64-bit RAM.
Scenario #4 - a pointer to a global array (declared outside a function):
char* array="string";
Same as scenario #3, except for the fact that the pointer (array
) is located in the data-section instead of in the stack and initialized once (during compilation) instead of every time the function is called (during execution).