Learn C
Posted on July 1, 2014
Tags: c
Code are commented to match with diagram
1 Pointers
1.1 Simple
int main(){
int e = 5;
int f = 9;
int *x;
= &e; //red arrow from x to e
x *x = 7;
("%d",e); //outputs 7
printf}
1.2 Point to same Value
- The red arrow is forcibly composable.
- Meaning if we have 2 red arrows, we must compose them.
int main(){
int e = 5;
int f = 9;
int *x;
int *y;
= &e; //red arrow from x -> e
x = x; //pink arrow via forcibly composed red arrows: y -> x, x -> e
y *y = 7;
("%d",e);
printf}
1.3 Change Value via Pointer Deref
int main(){
int e = 5;
int f = 9;
int *x;
int *y;
= &e; //red arrow from x to e
x = &f; //red arrow from y to f
y *x = *y; //Change values from 5 to 9
("%d",*x);
printf}
1.4 Swap
void swap(int *a, int *b){
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(){
int e = 5;
int f = 9;
(&e,&f);
swap("%d",e); //9
printf}
1.5 Nested Pointer
- Double pointer
int **h
gets 2 green arrows- First green arrow points to x
- Second green arrow Binds to the x’s red arrow
int main(){
int s[5] = {4,3,2};
int e = 5;
int f = 9;
int *x;
int *y;
int **h;
= &e; //red arrow from x to e
x = x; //red arrow from y to x
y
= &x; //first green arrow
h **h = 7; //second green arrow
("%d",e); //outputs 7 printf