int a ; // Define a variable called a
| |
| Main Memory |
a | allocated memory | address 1000
| |
a = 10 ; // Store the value 10 in a.
| |
| Main Memory |
a | 10 | address 1000
| |
int b = 20 ; // Define a variable b and assign 20 to it.
| |
| Main Memory |
a | 10 | address 1000
b | 20 | address 1004 (1000 + 4bytes)
| |
a = b ; // This will copy the value b and store it into a
| |
| Main Memory |
a | 20 | address 1000
b | 20 | address 1004 (1000 + 4 bytes)
| |
int * p ; // similer to variables but with a * added before the pointer name.
| |
| Main Memory |
a | 20 | address 1000
b | 20 | address 1004
p |new allocated mem. | address 1008 (1004 + 4 bytes)
| |
p = 10 ; //This is an ERROR, you cannot assign constant values to pointers!
p = &a ;// Assign the address (&) of variable a to pointer p
// Notice that we use the & operator to reffer to the address of a.
| |
| Main Memory |
a | 20 | address 1000
b | 20 | address 1004
p | 1000 | address 1008 (1004 + 4 bytes)
| |
*p = 30 ; // This will store 30 into (a) because the address of (a) is stored in (p)
// this is the same as a = 30 ;
| |
| Main Memory |
a | 30 | address 1000
b | 20 | address 1004
p | 1000 | address 1008 (1004 + 4 bytes)
| |
int var1 = 15;
int var2 = 25;
int * p = &var1;
*p = 45;
P = &var2;
*p = 35;
printf(“%d”,var1);
putc(‘\n’);
printf(“%d”,var2);
putc(‘\n’);
printf(“%d”,p);
/*
The result was:
45
25
2335120
*/
int i; // Allocates 4 bytes (or 32-bits)
short s; // Allocates 2 bytes (or 16-bits)
char c; // Allocates 1 byte (or 8 bits)
unsigned char uc; // Allocates 1 byte (or 8 bits)
unsigned short us;
unsigned int ui;
unsigned long ul;