0% found this document useful (0 votes)
15 views36 pages

CC213 Week05 Pointers

The document provides an overview of pointers in C programming, explaining their definition, declaration, initialization, and usage in functions. It covers key concepts such as the difference between pointer and normal variables, how to return multiple results from functions using pointers, and pointer arithmetic. Various examples illustrate the practical application of these concepts in programming.

Uploaded by

eng.ahmed.eg.94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views36 pages

CC213 Week05 Pointers

The document provides an overview of pointers in C programming, explaining their definition, declaration, initialization, and usage in functions. It covers key concepts such as the difference between pointer and normal variables, how to return multiple results from functions using pointers, and pointer arithmetic. Various examples illustrate the practical application of these concepts in programming.

Uploaded by

eng.ahmed.eg.94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CC213:Programming Applications

Week05

Pointers
Outline

• What is a Pointer variable?


• Functions returning multiple results
• Triple use for Asterisk (*)
• More Examples

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

countPtr count count


7 7
Pointer Variable Declarations
⚫ Pointer declarations
⚫ ‘*’ used with pointer variables
int *myPtr;
float *Ptr;
Char *strPtr;
⚫ Multiple pointers require using a * before each
variable declaration
int *myPtr1, *myPtr2;
⚫ Can declare pointers to any data type
Pointer Variable Initialization
⚫ Initialize pointers to:
⚫ 0 or NULL,
⚫ points to nothing (NULL preferred)
⚫ an address
⚫ points to certain place/address in memory

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.

Example: int *p;


int n = 84;
p = &n;
• Suppose that the int variable n is stored in the memory cell # 1024, then the
following figure shows the relationship between n and p.
n p
84 1024

4
Pointer Variable Initialization
(cont.) n p

84 1024

• A pointer variable such as p above, has two associated values:


• Its direct value, which is referenced by using the name of the
variable, p. In this example, this value is 1024. We can print
the direct value of a pointer variable using printf by using %p as
the place holder.
• Its indirect value, which is referenced by using the indirection
operator (*). So the value of *p is 84.
Reference Value
p Pointer(1024)
*p 84
5
Pointer Variable Initialization
(cont.)
int a=5;
int * ptr;
ptr=&a;

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

⚫ Allows you to change actual location in memory

⚫ Arrays are not passed with & because the array name is
already a pointer
⚫ * operator
⚫ Used as nickname for variable inside of function

void mydouble( int *number )


{ *number = 2 * ( *number ); }

Inside main(): mydouble(&y); 7


1 /* Example (2)
2 Cubing a variable using call-by-reference Outline
3 with a pointer argument */
Notice that the function prototype takes
4
a pointer to an integer (int *).
5 #include <stdio.h>
6 Notice how the address of number
7 void cubeByReference( int * ); is given
/* - cubeByReference
prototype */ Function prototype
8 expects a pointer (an address of a
9 int main() variable).
10 {
11 int number = 5; 1 Initialize variables
12
13 printf( "The original value of number is %d", number );
2. Call function
14 cubeByReference( &number );
15 printf( "\nThe new value of number is %d\n", number );
16 Inside cubeByReference, *nPtr is
17 return 0; used (*nPtr is number).
18 }
19
20 void cubeByReference( int *nPtr ) 3. Define function
21 {
22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
23 }
Program Output
The original value of number is 5
The new value of number is 125
Functions returning multiple results
(using Call by Reference)

• So far, we know how to pass inputs into a function and how to


use the return statement to send back at most one result from a
function.
• However, there are many situations where we would like a
function to return more than one result. Some Example are:
▪ Function to convert time in seconds into hours, minutes and seconds
▪ Function to find the quotient and remainder of a division
▪ Function to return maximum, minimum and average from a set of
values
• This ability to indirectly access a variable is the key
to writing functions that return multiple results.
• We declare such functions to have pointer variables
as their formal parameters.
Example 3:
/* shows how function can return void test1(int m, int n) {
multiple results */ m=5;
#include <stdio.h> n=24;
}
void test1(int m, int n);
void test2(int *m, int *n); void test2(int *m, int *n) {
void test3(int a, int *b); *m=5;
*n=24;
int main(void) { }
int a=10, b=16;
printf("a=%d, b=%d\n",a,b); void test3(int a, int *b) {
test1(a,b); a=38;
printf("a=%d, b=%d\n",a,b); *b=57;
test2(&a,&b); }
printf("a=%d, b=%d\n",a,b);
test3(a,&b);
printf("a=%d, b=%d\n",a,b);
system("pause");
return 0;
} 8
Three uses of Asterisk (*)
• We have now seen three distinct meanings of the symbol *
• As Multiplication operator: x * y => x times y
• In declaration int * p
▪ * tells the compiler that a new variable is to be a pointer
(read as “pointer to”)
▪ Thus, in this case, it is a part of the name of the type of the
variable.
• As unary indirection operator : x = * p
▪ It provides the content of the memory location specified by
a pointer. It mean “follow the pointer”.
▪ It can also stand on the left side of an assignment. * p = ‘K’
▪ Here the type depends on the variable being pointed – char
in the above case.
▪ It is a common mistake by students to interpret the above as
a pointer type. 9
Example 4:
/* computes the area and circumference of a circle, given its radius */
#include <stdio.h>
void area_circum (double radius, double *area, double *circum);
int main (void) {
double radius, area, circum ;
printf ("Enter the radius of the circle > ") ;
scanf ("%lf", &radius) ;
area_circum (radius, &area, &circum) ;
printf ("The area is %f and circumference is %f\n", area, circum) ;
return 0;

void area_circum (double radius, double *area, double *circum) {


*area = 3.14 * radius * radius ;
*circum = 2 * 3.14 * radius ;
}

10
Example 5:
/* Takes three integers and returns their sum, product and average */
#include<stdio.h>

void myfunction(int a,int b,int c,int *sum,int *prod, double *average);

int main (void) {


int n1, n2, n3, sum, product;
double av_g;
printf("Enter three integer numbers > ");
scanf("%d %d %d",&n1, &n2,&n3);
myfunction(n1, n2, n3, &sum, &product, &av_g);
printf("\nThe sum = %d\nThe product = %d\nthe avg =%f\n",sum, product,av_g);
system("pause");
return 0;
}

void myfunction(int a,int b,int c,int *sum,int *prod, double *average) {


*sum=a+b+c;
*prod=a*b*c;
*average=(a+b+c)/3.0;
}
11
Example 6:
/* takes the coefficients of quadratic
equation a, b and c and returns its roots
*/
#include<stdio.h>
#include<math.h>
void quadratic(double a,double b,
double c, double *root1, double *root2)
void quadratic(double a,double b, double c, double *root1,
{
double *root2);
double desc;
int main(void) { desc =b*b-4*a*c;
double a,b,c,r1,r2; if(desc < 0) {
printf("Please enter coefficients of the equation: [a b c] > "); printf("No real roots\n");
scanf("%lf%lf%lf",&a,&b,&c); system("pause");
exit(0);
quadratic(a,b,c,&r1,&r2); }
else {
printf("\nThe first root is : %f\n",r1); *root1=(-b+sqrt(desc))/(2*a);
printf("The second root is : %f\n",r2); *root2=(-b-sqrt(desc))/(2*a);
system("pause"); }
return 0;
}
}
Example 7:
/* reads & swaps the values between 2 integer variables
*/
#include <stdio.h>
void readint(int *a, int* b);
void swap (int *a, int *b); void swap (int *a, int*b) {
int main (void ) { int temp;
int num1,num2; temp=*a;
readint(&num1,&num2); *a=*b;
printf("before swapping num1= %d, num2=%d\n", num1,num2); *b=temp;
swap(&num1,&num2); }
printf("after swapping num1= %d, num2=%d\n", num1,num2);
system("pause");
return 0;
}

void readint (int *a, int *b) {


Because a and b
printf("enter first integer number > ");
are pointer
scanf("%d",a);
variables, we do not
printf("enter second integer number > ");
use the & operator
scanf("%d",b);
for scanf.
} 13
Pointer Expressions and
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
Pointer Expressions and
Arithmetic
operation Description

p++, p-- Increment(decrement) p to point to the next element,


it is equivalent to p+=1 (p-=1)
p+i, (p-i) Point to i-th element beyond (in front of) p but value
of p is fixed
p[i] Equivalent to p+i

p+n(integer) n must be an integer, its meaning is offset

p-q Offset between pointer p and pointer q

p+q, p*q, p/q, p%q invalid

Relational operator of valid, including p>q, p<q, p==q,


two pointers p, q p>=q ,p<=q, p!=q
Pointer Expressions and
Arithmetic
⚫ Pointer comparison ( <, == , > )
⚫ See which pointer points to the higher numbered
array element (index)
⚫ Also, see if a pointer points to 0
Example 8:
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int *ptr=( int *)1000; double *p=(double *)1000;
ptr=ptr+1;
p=p+3;
printf(" %d",ptr);
return 0;
printf(" %d",p);
return 0;
}
}

Output: 1004 Output: 1024


Example 9:
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int *p=(int *)1000; float *p=(float *)1000;
int *temp; float *q=(float *)2000;
temp=p; printf("Difference= %d",q-p);
p=p+2; return 0;
printf("%d %d\n",temp,p); }
printf("difference= %d",p-temp); Output: Difference= 250
return 0;
}
Output: 1000 1008
Difference= 2
Arrays and Pointers
Arrays and Pointers
Note

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:

To access an array, any pointer to the first element can be


used instead of the name of the array.
Example – 3 (Array and pointers)
Example 13:
#include <stdio.h>
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{ int i;
ptr = &my_array[0]; /* point our pointer to the first element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{ printf("my_array[%d] = %d ", i , my_array[i] );
printf(“\t ptr + %d = %d\n", i , *(ptr + i) ); }
return 0;
}
Example 14:
Example – 5 (swap with array index)
(swap with array index)
#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;
}
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};

z[0] = a; // same as &a[0];


z[1] = a + 1; // same as &a[1];
z[2] = a + 2; // same as &a[2];
z[3] = a + 3; // same as &a[3];

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

You might also like