3. • A variable declared as an array represents a contiguous
region of memory in which the array elements are stored.
int x[5]; // an array of 5 4-byte ints.
• All arrays begin with an index of 0
• An array identifier is equivalent to a pointer that references
the first element of the array
– int x[5], *ptr;
ptr = &x[0] is equivalent to ptr = x;
• Pointer arithmetic and arrays:
– int x[5];
x[2] is the same as *(x + 2), the compiler
will assume you mean 2 objects beyond
element x.
Arrays and Pointers
0
1
2
3
4
10 2 3
little endian byte ordering
memory layout for array x
Dr. Yousaf, PIEAS
4. The Relationship b/w Pointers and Arrays
• Pointers have close relationship with arrays and strings
– Array name is itself a pointer. It means the name of the
array is the address of the first element of the array.
– Pointers can do array subscripting operations
• Declare an array b[ 5 ] and a pointer Ptrb
• b[5] = {4, 7, 9, 10, 56};
• int *ptrb
• Array name b is also the address of this
array.
• Ptrb = b; // Most important to note that we
have not used & with b. WHY?
• Because actually b itself is the address of
first element of the array b[5].
i.e. Ptrb = &b[ 0 ]
Explicitly assigns bPtr to address of first element of b
Dr. Yousaf, PIEAS
5. • int b[5] = {4, 7, 9, 10, 56};
• int *ptrb, *ptr2
• ptrb = b;
• ptr2 = &b[ 0 ]
// Are ptrb and ptr2 equal? Yes.
printf(“ptrb = %d”, ptrb);
printf(“ptr2 = %d”, ptr2);
They will have the same addresses
Dr. Yousaf, PIEAS
The Relationship b/w Pointers and Arrays
6. – Element b[ 3 ]
• Can be accessed by *( ptrb + 3 )
–Where 3 is the offset, called pointer/offset
notation
• Can be accessed by ptrb[ 3 ]
–Called pointer/subscript notation
–ptrb[ 3 ] same as b[ 3 ]
• Can be accessed by performing pointer
arithmetic on the array itself
*( b + 3 )
Dr. Yousaf, PIEAS
The Relationship b/w Pointers and Arrays
7. Array as a Pointer
• Array: sequence of identical objects in memory
• int a[10]; means space for ten integers
By itself, a is the address of the first integer
*a and a[0] mean the same thing
The address of a is not stored in memory: the compiler
inserts code to compute it when it appears
Dr. Yousaf, PIEAS
8. Pointer Arithmetic
If we define an array we can use pointers to access it
int i[7]; /* An array of 7 ints */
int *j; /* A pointer to an int*/
j= i; /* j points at the start of i*/
*j= 3; /* Same as i[0]= 3 */
j= &i[0]; /* Same as j= i */
j= j+1; /* Move j to point at i[1]*/
Dr. Yousaf, PIEAS
9. Pointer Expressions and Pointer
Arithmetic
• Arithmetic operations can be performed on pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Operations meaningless unless performed on an
array
Dr. Yousaf, PIEAS
10. Pointer Expressions and Pointer Arithmetic
5 element int array on machine with 4 byte ints
– int v[5];
– int *vptr;
– vptr = v;
– vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the
machine has 4 bytes ints, so it points to address
3008
pointer variable vPtr
v[0] v[1] v[2] v[4]v[3]
3000 3004 3008 3012 3016
location
Dr. Yousaf, PIEAS
11. Pointer Expressions and Pointer Arithmetic
• Subtracting pointers
– Returns number of elements from one to the other.
5 element int array on machine with 4 byte ints
int v[5];
int *vptr1, *vptr2;
vptr1 = v; // actually vptr1 = v[0];
vptr2 = &v[2];
vPtr2 – vPtr1; //would produce 2, i.e if two pointers are
pointing to the same variable, the difference between their
values will be equal to the number elements between them.
• Pointer comparison ( <, == , > )
– See which pointer points to the higher numbered array
element
– e.g if (vptr2 > vptr 1)
rest of the code here
Dr. Yousaf, PIEAS
13. // Printing the elements of an array without using pointer
#include<stdio.h>
int main()
{
int i, x[5] ={10, 20, 30, 40, 50};
for (i = 0; i<5;i++)
printf("n x = %d", x[i]);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
14. // Printing the elements of an array using pointer
#include<stdio.h>
int main()
{
int i, x[5] ={10, 20, 30, 40, 50}, *ptrx;
ptrx = x; // important to observe that there is no & sign with x.
// x itself is an address of the first element stored in array x
for (i = 0; i<5;i++)
{
printf("n x = %d",*ptrx);
ptrx++; // see the increment in ptrx and its use
}
getchar();
return 0;
} Dr. Yousaf, PIEAS
15. /* C program to determine and print the largest number in an
array (no use of pointers) */
#include<stdio.h>
int main()
{
int i, max, x[5] ={23, 78, 99, 2, 37};
max = x[0];
for (i = 0; i<5;i++)
{
if (x[i] > max)
max = x[i];
}
printf("n max = %d",max);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
16. /* C program to determine the largest number in an array, and
then print it using a pointer */
#include<stdio.h>
int main()
{
int i, max, x[5] ={23, 78, 99, 2, 37}, *ptrmax;
max = x[0];
for (i = 0; i<5;i++)
{
if (x[i] > max)
max = x[i];
}
ptrmax = &max;
printf("n max = %d", *ptrmax);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
17. Solve a problem
Dr. Yousaf, PIEAS
Try to write a program that calculates average of
three numbers, you have done this program before,
here try to do it using pointers, i.e. use pointers only.
18. Solve a problem
Dr. Yousaf, PIEAS
Try to write a program that swaps the values of two
integer variables, you have to do it using pointers
i.e. any modifications in the values of integer
variables should be done using pointers.
20. Pass by Value/ Pass by Reference
• Normally when we send a variable to a function we
make a COPY of the variable.
• This is called pass by value. A value is passed and
this copy of the variable arrives at the function. The
original doesn’t change.
• The value of a variable can also be pass by reference
• In this case, any change in the value of this variable
made within a function changes the original value.
Dr. Yousaf, PIEAS
21. What's the point of pointers?
• When we use & to pass a pointer to a variable
into a function we CAN change the value of the
variable within the function.
• This is called pass by reference.
Dr. Yousaf, PIEAS
22. Calling Functions by Reference
Call by reference with pointer arguments
–Pass address of argument using & operator
–Allows you to change actual location in
memory
Dr. Yousaf, PIEAS
23. // Passing arguments by reference
#include <stdio.h>
void myfunc(int *a, int *b, int *c);
int main()
{
int x = 2, y = 4, z = 6;
printf("n Before calling
by_reference(), x=%d, y=%d,z= %d.",
x, y, z); //x = 2, y = 4, z = 6.
my_func(&x, &y, &z);
printf("nn After calling
by_reference(), x=%d, y=%d, z=%d.",
x, y, z); //x = 0, y = 0, z = 0.
getchar(); return(0);
}
void myfunc(int *a, int *b,
int *c)
{
*a = 0;
*b = 0;
*c = 0;
printf("nn Within function
by_ref(), x= %d, y = %d, z =
%d.", *a, *b, *c);
//x = 0, y = 0, z = 0.
}
Dr. Yousaf, PIEAS
24. Calling Functions by Reference
Use of * operator
// Passing arguments by reference
#include <stdio.h>
void my_double(int *number )
int main()
{
int number;
pintf(“Enter an integer number);
scanf(“%d”, &number);
my_double(&number) ;
printf(“%d”, number);
getchar();
}
void my_double( int *number )
{
*number = 2 * ( *number );
}
//*number used as alias/nickname for variable inside function
Dr. Yousaf, PIEAS
25. Changing an argument within a function
void square_num (int *);
int main()
{
int p= 5;
square_num (&p);
printf ("P is now %dn",p);
return 0;
}
void square_num (int *num)
{
(*num)= (*num) * (*num);
}
Prototype a function
taking a POINTER
Pass the address of p to square function
Now the function has changed p to 25
Remember * gives
the value the pointer
points at
Dr. Yousaf, PIEAS
27. Calling Functions by Reference
Arrays are not passed with & because
the array name is already a pointer
(we have already studied)
Dr. Yousaf, PIEAS
28. /*Pass by reference (Page 365)
//Pass by reference Example Page
366
If names of variables in main and
the calling function are similar */
#include<stdio.h>
void add_num_inArray(int x[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",x[i]);
}
getchar(); return 0;
}
void add_num_inArray(int
x[])
{
int i;
for (i = 0; i<5; i++)
{
x[i] = x[i] + 5;
}
}
Pass by Reference
Dr. Yousaf, PIEAS
29. /* Pass by reference
If names of variables in main and the
calling function are different */
#include<stdio.h>
void add_num_inArray(int k[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",x[i]);
}
getchar(); return 0;
}
void add_num_inArray(int k[])
{
int i;
for (i = 0; i<5; i++)
{
k[i] = k[i] + 5;
}
}
Pass by Reference
Dr. Yousaf, PIEAS
30. /* Define an array in main. Pass that
array to a function that should
determine the maximum number.
// Return the maximum number
from that function to main and then
print it in main.
No use of pointers */
#include<stdio.h>
int find_max(int k[]);
int main()
{
int max, x[5] ={23, 78, 99, 2, 37};
max = find_max(x);
printf("n max = %d",max);
getchar();
return 0; }
int find_max(int k[])
{
int i, max = k[0];
for (i = 0; i<5;i++)
{
if (k[i] > max)
max = k[i];
}
return max;
}
Dr. Yousaf, PIEAS
31. /* Define an array in main. Pass that
array to a function that should
determine the maximum number
// Return the address of that max
number (using pointer) from the
function to main and then print it in
main. */
#include<stdio.h>
int* find_max(int k[]);
int main()
{
int *ptrmax, x[5] ={23, 78, 99, 2, 37};
ptrmax = find_max(x);
printf("n max = %d",*ptrmax);
getchar();
return 0; }
int* find_max(int k[])
{
int *ptrmax;
int i;
int max = k[0];
for (i = 0; i<5;i++)
{
if (k[i] > max)
max = k[i];
}
ptrmax = &max;
return ptrmax;
}
Dr. Yousaf, PIEAS
32. /* Define an array in main. Pass that array
to a function that should add an integer to
each element of that array. Return the
address of the new array (using pointer)
from the function to main and then print it
in main. */
#include<stdio.h>
int* add_num_inArray(int k[]);
int main()
{
int i, *ptr_added_array, x[5] ={23, 78, 99, 2,
37};
ptr_added_array = add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",*ptr_added_array);
ptr_added_array++;
}
getchar();
return 0; }
int* add_num_inArray(int
k[])
{
int i;
int new_array[5];
for (i = 0; i<5; i++)
{
new_array[i] = k[i] + 5;
}
return new_array;
}
Dr. Yousaf, PIEAS
33. /* Define an array in main. Pass that array to a
function that should add an integer number to
each of the element of that array.
Also correspond the added_array of main
function and new_array of main function in the
calling statement of the main function.
// In fact, here array names are being used as
pointers. */
#include<stdio.h>
void add_num_inArray(int k[], int new_array[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
int added_array[5];
add_num_inArray(x, added_array);
for (i = 0; i<5;i++)
{
printf("n %d", added_array[i]);
}
getchar();
return 0; }
void add_num_inArray(int k[],
int new_array[])
{
int i;
for (i = 0; i<5; i++)
{
new_array[i] = k[i] + 5;
}
}
Dr. Yousaf, PIEAS
34. We can pass 2D arrays to and from
functions
• Example prototype for function:
void process_array (int X[3][6]);
void process_array (int array[3][6])
{
/* Do stuff to the array */
}
int thearray[3][6];
process_array(thearray);
Call the array with this (in main or other function)
And write the function with
Dr. Yousaf, PIEAS
35. // Add two matrices in main and print them
// No use of pointers
#include<stdio.h>
int main()
{
int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = { {5,6},{7,8} }, result_mat[2][2];
int i,j;
for (i = 0; i<2;i++)
for (j = 0; j<2; j++)
result_mat[i][j] = mat1[i][j] + mat2[i][j];
for (i = 0; i<2;i++)
{
printf("n");
for (j = 0; j<2; j++)
printf("%d t", result_mat[i][j]);
}
getchar();
return 0; }
Dr. Yousaf, PIEAS
36. /*Declare two matrices in main. Pass them
to a function. Add these in a function.
Print the results in main
Use array name as pointers */
#include<stdio.h>
void add_mat(int x[2][2], int y[2][2], int
z[2][2]);
int main()
{
int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = {
{5,6},{7,8} }, res_mat[2][2];
int i,j;
add_mat(mat1, mat2, res_mat);
for (i = 0; i<2;i++)
{
printf("n");
for (j = 0; j<2; j++)
printf("%d t", res_mat[i][j]);
}
getchar(); return 0; }
void add_mat(int x[2][2],
int y[2][2],int z[2][2])
{
int i, j;
for (i = 0; i<2;i++)
for (j = 0; j<2; j++)
z[i][j] = x[i][j] + y[i][j];
}
Dr. Yousaf, PIEAS
37. • We can also have pointer to pointer:
• We can even have pointers to functions:
• If you want to use them then feel free.
Pointer to Pointer
int number= 5;
int *ptrtonumber;
int **ptrtoptrtonumber;
ptrtonumber= &number;
ptrtoptrtonumber= &ptrtonumber;
*(*ptrtoptrtonumber)= 6;
5
ptrtonumber
ptrtoptrtonumber
number
Dr. Yousaf, PIEAS
39. • Loop
– Group of instructions computer executes repeatedly
while some condition remains true
• Counter-controlled repetition
– Definite repetition: know how many times loop will
execute for (i = 0; i < 12; i++)
– Control variable (e.g i)used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
Dr. Yousaf, PIEAS
40. Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires
– The name of a control variable (or loop counter)
– The initial value of the control variable
– A condition that tests for the final value of the
control variable (i.e., whether looping should
continue)
– An increment (or decrement) by which the control
variable is modified each time through the loop
Dr. Yousaf, PIEAS
41. Essentials of Counter-Controlled
Repetition• Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition
condition
printf( "%dn", counter );
++counter; // increment
}
– The statement
int counter = 1;
• Names counter
• Declares it to be an integer
• Reserves space for it in memory
• Sets it to an initial value of 1
Dr. Yousaf, PIEAS