CC213 Week05 Pointers
CC213 Week05 Pointers
Week05
Pointers
Outline
2
What is a Pointer Variable?
⚫ Pointer is a variable just like other
variables of c but only difference is
unlike the other variable it stores the
memory address of any other variables
of c.
⚫ This variable may be type of int, char,
array, structure, function or any other
pointers.
Pointer Variable vs Normal
Variable
⚫ Normal variables
⚫ Contain a specific value (direct reference)
⚫ Pointer variables
⚫ Contain memory addresses as their values
int y = 5;
int *yPtr;
yPtr = &y; // yptr is the address of y
// yPtr “points to” y
Pointer Variable Initialization
(cont.)
• Pointers like any other variables must be declared before they can be used.
• A pointer variable is declared by preceding its name with an asterisk.
4
Pointer Variable Initialization
(cont.) n p
84 1024
About variable a:
About variable ptr:
⚫ 1. Name of variable : a
⚫ 4. Name of variable : ptr
⚫ 2. Value of variable which it
⚫ 5. Value of variable which it
keeps: 5
keeps: 1025
⚫ 3. Address where it has stored
⚫ 6. Address where it has stored
in memory : 1025 (assume)
in memory : 5000 (assume)
Example 1:
• The following example demonstrate the relationship between
a pointer variable and the character variable it is pointing to.
/* Shows the relationship between a pointer variable
* and the character variable it is pointing to */
#include<stdio.h>
int main(void) {
char g= 'z';
char c= 'a';
char *p;
p= &c;
printf("%c\n", *p);
p=&g;
printf("%c\n", *p);
*p='K';
printf("%c\n", g);
return 0;
}
6
Functions returning one result
(using Call by Reference)
⚫ Call by reference with pointer arguments
⚫ Pass address of argument using & operator
⚫ Arrays are not passed with & because the array name is
already a pointer
⚫ * operator
⚫ Used as nickname for variable inside of function
10
Example 5:
/* Takes three integers and returns their sum, product and average */
#include<stdio.h>
a &a[0]
a is a pointer only to the first element—not the whole array.
Note
The name of an array is a pointer constant;
it cannot be used as an lvalue.
Example 10:
Example 11:
Example 12:
int main() {
int i, j;
int Arr[N]={1,2,3,4,5};
for (i=0; i < N/2 ; i++)
swap ( & Arr [ i ] , & Arr [ (N-1) – i ] );
return0;
}
Example 15:
Example – 6 (swap with pointers)
(swap with pointers)
#include<stdio.h>
# define N 5
void swap (int *a, int *b){
int temp = *a;
*a = *b;
*b = temp; }
int main() {
int i, j;
int Arr[N]={1,2,3,4,5};
for (i=0; i < N/2 ; i++)
swap ( Arr + i , Arr + (N-1) – i );
return0;
}
Arrays of Pointers
⚫ Arrays can contain pointers to …..
Array of Pointers
Arrays of Pointers
int x = 4;
int *y = &x;
int *z[4] = {NULL, NULL, NULL, NULL};
int a[4] = {1, 2, 3, 4};
for (x=0;x<4;x++)
printf("\n %d --- %d ",a[x],*z[x]);
Arrays of Pointers
⚫ Arrays can contain pointers to (array)
The End