There are several different pieces at play here.
The first is the difference between declaring an array as
int array[n];
and
int* array = malloc(n * sizeof(int));
In the first version, you are declaring an object with automatic storage duration.
This means that the array lives only as long as the function that calls it exists.
In the second version, you are getting memory with dynamic storage duration,
which means that it will exist until it is explicitly deallocated with free.
The reason that the second version works here is an implementation detail of how
C is usually compiled. Typically, C memory is split into several regions, including
the stack (for function calls and local variables) and the heap (for malloced objects)
. The stack typically has a much smaller size than the heap; usually it's something
like 8MB. As a result, if you try to allocate a huge array with
int array[n];
Then you might exceed the stack's storage space, causing the segfault.
On the other hand, the heap usually has a huge size (say, as much space as
is free on the system), and so mallocing a large object won't cause an
out-of-memory error.
In general, be careful with variable-length arrays in C. They can easily exceed
stack size. Prefer malloc unless you know the size is small or that you really
only do want the array for a short period of time.
----------------------------------------------------------------------------------
*array[] means array of pointers, in your example:
char *somarray[] = {"Hello"};
somarray[] is array of char*. this array size is one and contains address to
on string "Hello" like:
somarray[0] -----> "Hello"
somarray means address of first element in array.
&somarray means array address
*somarray means value of first element
Suppose address of "Hello" string is for example 201, and array somaaray at 423
address, then it looks like:
+----+----+----+---+---+----+----+----+---+----+
| `H`| 'e'|'l'|'l'|'o'| '\0'|
+----+----+----+---+---+----+----+----+---+---+----+
201 202 203 204 205 206 207 208 209 210 2
^
|
+----+----+
| 201 |
+----+----+
423
somarray
and:
somarray gives 423
&somarray gives 423
*somarray gives 201
Point to be notice somarray and &somarray gives same value but semantically
both are different. One is address of first element other is address of array.
To embed this program on your website, copy the following code and paste it into your website's HTML: