When you write
int a[10];
you say
"assign 10 blocks of memory to me each of which can store an integer
value".
By default when you put this definition in a block (part of code surrounded by {
and }
), you cannot use the variable a outside of block.
Why? Suppose the program is executing instructions inside of a block and it came across this definition. It allocates some memory to store the variable a. When the program finds that it has reached the end of block, it destroys the whole memory it has allocated while it was in the block. So, when you refer a in code after the closing brace (}
), it doesn't know what a is because the memory was destroyed.
On the other hand when you write
int* a = (int*) malloc(10*(sizeof(int)));
you say
"assign 10 blocks of special memory to me each of which can store an
integer value"
. This special memory is called heap memory. It is special because, it is present in a new place that is never destroyed (unless you ask it to). So, you can access it even outside the block.