int my_array[5] = {0};
int *my_pointer = 0;
my_pointer = &my_array; // compiler error
my_pointer = my_array; // ok
If my_array
is address of array then what does &my_array
gives me?
I get the following compiler error:
error: cannot convert 'int (*)[5]' to 'int*' in assignment
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
You cannot swap the address of array elements. The array elements are all stored in sequence in memory. If an integer takes 4 bytes in memory, for an array of size 10, a total of 40 contiguous bytes are taken in memory.
Array VariablesIt cannot be assigned a different array or a pointer to a different array. Think about it, if you have a variable A that points to an array and you were able to change the address of A to something else, what happens to the memory pointed to by the A array.
An array of pointers is useful for the same reason that all arrays are useful: it lets you numerically index a large set of variables. Below is an array of pointers in C that points each pointer in one array to an integer in another array. The value of each integer is printed by dereferencing the pointers.
my_array
is the name of an array of 5 integers. The compiler will happily convert it to a pointer to a single integer.
&my_array
is a pointer to an array of 5 integers. The compiler will not treat an array of integers as a single integer, thus it refuses to make the conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With