I'm trying to change array's variables address by swapping the address, not the value. I have a function that swap the numbers in the array: a[0]=a[9] , a[9]=a[0], a
CodePudding user response:
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. The array a
points to the address of the beginning of these 40 bytes and when you index it, the index is multiplied by sizeof(int) = 4
. Therefore, the address of a[1]
equals the address of a
4, and the address of a[9]
equals the address of a
9 * 4.
As you have shown in the image, the addresses of the array elements are all contiguous and differ by just 4 bytes. You are able to say for example a = a 20
which causes a[0]
to point to a[5]
, but then the rest of the array elements are also shifted and will point to after that as explained above. Technically, you can only change where the beginning of the array points to, and you are not able to change where the middle of the array points to.