Pointers Value, Address, and Pointer
Values and Addresses int x, y, z; y x z values of x, y, and z x is 5 y is 10 z is 15 addresses of x, y, and z &x is &y is &z is x = 5; y = x + 5; z = y + 5;
Example 1 #include int main(void) { int x, y, z; x = 5; y = 10; z = x + y; printf("The value of x is: %3d\n", x); printf("The value of y is: %3d\n", y); printf("The value of z is: %3d\n", z); printf("\n"); printf("The address of x is: %d\n", &x); printf("The address of y is: %d\n", &y); printf("The address of z is: %d\n", &z); return(0); }
Pointers int *p, *q; y x z values of p and q p = &x; q = &y; z = *p + *q + 3; p q p is q is addresses of p and q &p is &q is values pointed by p and q *p is 5 *q is 10
Example 2 #include int main(void) { int x, y, z; int *p, *q; x = 5; y = 10; p = &x; q = &y; z = *p + *q + 3; printf("The address of x is: %d\n", &x); printf("The address of y is: %d\n", &y); printf("\n"); printf("The value of p is: %3d\n", p); printf("The value of q is: %3d\n", q); printf("\n"); printf("The value of x is: %3d\n", x); printf("The value of y is: %3d\n", y); printf("\n"); printf("The value of x is: %3d\n", *p); printf("The value of y is: %3d\n", *q); printf("\n"); printf("The value of z is: %3d\n", z); return(0); }
Example 3 int x, y; int *px, *py; x = 3; y = 5; px = &x; py = &y printf(“%d”, *px); *px = 1; printf(“%d”, *px); *py = 7; py = px; printf(“%d”, *px);
Example 4 – Scope of variable #include void DoIt(int x); int main(void) { int x; x = 3; printf("Before calling function: %d\n", x); DoIt(x); printf("After calling function: %d\n", x); return(0); } void DoIt(int x) { x = 44; printf("Inside the function: %d\n", x); }
Example 5 – Scope of variable #include void DoIt(int *x); int main(void) { int x; x = 3; printf("Before calling function: %d\n", x); DoIt(&x); printf("After calling function: %d\n", x); return(0); } void DoIt(int *x) { *x = 44; printf("Inside the function: %d\n", *x); }
Sort Problem: Sort three numbers in ascending order Analysis: Put minimum in 1 st, next minimum in 2 nd Design: – Compare 1 st &2 nd, put smaller in 1 st, – Compare 1 st & 3 rd, put smaller in 1 st, – Compare 2 nd & 3 rd, put smaller in 2 nd – Use function for sort called MySort takes three pointers and sorts the contents. Does not return a value – Use a function for exchanging two values called xChange which takes two pointers and exchanges the contents.
Sort Code: Test: – Try output – Try output – Try output – Try output Maintain: Correct errors, make improvements, add new functionality