This is completely wrong:
int arr[3] = (int *)malloc(sizeof(int)*3);
because you are trying to allocate memory to an array which is not allowed.
It should be:
int * arr = malloc(sizeof(int)*3);
When you do this, the in-memory view would be something like this (assuming malloc
is success):
+-----------+
| | | |
+-----------+
^
|
arr
arr
is a pointer pointing to the base address of the memory.
arr[1]
is the first element of array (a single element of integer array arr
) and
&arr[1]
is the address of first element of array arr
.
+-----------+
| | | |
+-----------+
^
|
&arr[1]
When you take input in first element of array arr
you have to pass the address of first element of array to scanf()
which is &arr[1]
.
&
used with scanf()
arguments has nothing to do with dynamic allocation. If you want to take input in an element of fixed length array (size determined at compile time), the syntax will be same:
int arr[3];
scanf("%d", &arr[1]);
Please let me know if you have any further questions.