Pointers in C: Spring Semester 2011 Programming and Data Structure 1
Pointers in C: Spring Semester 2011 Programming and Data Structure 1
int arr[20];
:
&arr; -- Pointing at array name.
• Example:
int *count;
float *speed;
• Once a pointer variable has been declared,
it can be made to point to a variable using
an assignment statement like:
int *p, xyz;
:
p = &xyz;
– This is called pointer initialization.
int a, b;
int *p; b = a;
Equivalent to
:
p = &a;
b = *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (”a=%d b=%d \n”, a, b);
} a=40 b=40
x = 10 ;
ptr = &x ;
y = *ptr ;
printf (”%d is stored in location %u \n”, x, &x) ;
printf (”%d is stored in location %u \n”, *&x, &x) ;
printf (”%d is stored in location %u \n”, *ptr, ptr) ;
printf (“%d is stored in location %u \n”, y, &*ptr) ;
printf (“%u is stored in location %u \n”, ptr, &ptr) ;
printf (“%d is stored in location %u \n”, y, &y) ;
*ptr = 25;
printf (”\nNow x = %d \n”, x);
}
Output:
Now x = 25
Output:
int x, y;
printf (”%d %d %d”, x, y, x+y);
Three-step algorithm:
1. Read in three integers x, y and z
2. Put smallest in x
• Swap x, y if necessary; then swap x, z if necessary.
3. Put second smallest in y
• Swap y, z if necessary.
#include <stdio.h>
main()
{
int x, y, z;
………
scanf (”%d %d %d”, &x, &y, &z);
if (x > y) swap(&x,&y);
if (x > z) swap(&x,&z);
if (y > z) swap(&y,&z);
………
}
TO BE DISCUSSED LATER