suppose I have the following code:
#define SIZE 5
### FIRST OPTION ###
int main(int argc , char** argv){
### SECOND OPTION ###
return 0;
}
I have checked online and couldn't really understand what will be the difference between those three code statements (on compile and runtime) when I write them instead of first option line and second option line (each statement will be wrote individually) :
struct my_struct array[SIZE]
static struct my_struct array[SIZE]
struct my_struct** array = (struct my_struct**)malloc(SIZE*sizeof(struct my_struct*))
Michael
Option '1' can be used to define your array in a global scope or in a scope of a function, like main. In the following example 'array' is declared in the global scope and is potentially visible to any other module in at link time (if such a module declares it as 'extern'. There is only one copy of this array in the program.
file1.c
struct my_struct array[SIZE];
int main() {
...
array[0] = ...;
}
this file can access the declaration in file1.c
file2.c
extern struct my_struct array[SIZE];
void foo() {
...
array[1] = array[0];
}
Now, if you declare it inside a function, than a new copy of the array will be allocated (in stack) every time the function is called.
int foo() {
struct my_struct array[SIZE];
....
}
It will be visible inside of the function only. 'main' is a normal function and the rule works there as well.
using static (#2) changes the meaning of allocation. If used outside, there will be only one copy of the data associated with this particular file. It will be visible from inside the file, but not from outside.
static struct my_struct array[SIZE];
int main() {
...
array[0] = ...;
}
if you use it inside the function, than it will be only a single copy of it associated with this function. It will not change between calls to the same function and will keep previous values. It also be visible from inside the function only.
int foo() {
static struct my_struct array[SIZE];
....
array[0].counter++;
}
for #3 all the global/static rules stay the same, but just for the pointer. The pointer contains an address of the memory where you dynamically allocated the array.