Unable to figure out the dependency between the address of the specific variables, as appeared to the C complier, and the actual underlying hardware.
Consider example 1, after compiling of this code with cc t2.c
, and executing it, it looks, it is not working as expected, the addresses of px
and py
are not getting interchanged for whatever reason.
Example 1:
#include <stdio.h>
void swap(int *,int *);
int main(){
int x=3;
int y=2;
int *px;
int *py;
px=&x;
py=&y;
printf("px = %x\npy = %x\n",&px,&py);
swap(px,py);
printf("After the swap\npx = %x\npy = %x\n",&px,&py);
}
void swap(int *px,int *py){
int temp;
temp=*px;
*px=*py;
*py=temp;
}
gdb of example 1:
6 int x=3;
(gdb) n
7 int y=2;
(gdb) n
10 px=&x;
(gdb) p x
$1 = 3
(gdb) p &x
$2 = (int *) 0x7efff5cc
(gdb) p px
$3 = (int *) 0x0
(gdb) p &px
$4 = (int **) 0x7efff5d4
(gdb) n
11 py=&y;
(gdb) p px
$5 = (int *) 0x7efff5cc
(gdb) p &px
$6 = (int **) 0x7efff5d4
....
pi@readonly:~/new$ cc t2.c
pi@readonly:~/new$ a.out
px = 7ea765fc
py = 7ea765f8
After the swap
px = 7ea765fc
py = 7ea765f8
Example 2:
int x = 1, y = 2 ;int *ip; /* ip is a pointer to an int */
ip = &x; /* ip now points to x */
y = *ip; /* y is now 1 */
*ip = 10; /* x is now 10 */
*ip = *ip + 1; /* x is now 11 */
*ip += 1; /* x is now 12 */
++*ip; /* x is now 13 */
(*ip)++; /* x is now 14, parentheses are required */
Ex 1 Q:
1) Am I understand correctly, that, starting from the $5
, px
- is exactly the same variable as x
, except it has its value set to 0x7efff5cc
in hexadecimal, which is simply the address of the variable x
in the memory??
2) If we use int *ip
declaration, does it mean, that variable ip
has the value equals to the address of int
? Then, what is the address of int
, in hexadecimal?
3) What does mean the address of the variable, what is this 0x7efff5cc
? In other words:
I know, there are RAM, L2, L3, L1 caches of CPU, ROM. So, Address of which specific memory this number is representing?
How many such
0x7efff5cc
can hold those specific type of memory? Or, where I can check it on Linux system?
4) What does (int **)
notation mean?
5) What's wrong with the program, how to fix it, in order to get the addresses of px
and py
interchanged after being passed as an argument values to the function swap
?
Ex 2 Q:
5) Regarding the notation, am I understand it correctly, that as soon as we declare that the variable ip
is a pointer to int
, via int *ip
, we cannot assign, for example, the decimal value to ip
, later on, using assignment like: ip = 10;
since, after the variable has been declared as pointer, it is used solely for holding the addresses of other variables, to which ip
"is pointing to", in hexadecimal?