0% found this document useful (0 votes)
12 views39 pages

Pointers in C

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

Pointers in C

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

POINTERS IN C

CSC-103 Programming Fundamentals


CSC-141 Introduction to Computer Programming

Lecture

Slides prepared by: Dr Mohammad kaleem


Lecture Outline
• What is a Pointer?
• Declaring Pointers to Integers, Double, Char
• Dereferencing Operator
• Initializing Pointers
• Declaring more than one Pointers
• Constant Pointers
• Pointers and Functions
• Pointers and Arrays
• Array traversal using pointers
• Sorting and searching elements in an array
• Arrays of structure
• Increment / Decrementing a Pointer
• Pointer Arithmetic
• Pointers Comparison
• Strings (character array)
• string functions, Null string
• Pointers to a Pointer
• An Array of Pointers
• Storing Pointers in Array of Pointers 2
• Pointer and structures
What is a Pointer?
• Is a special kind of variable in which we store memory addresses
(Instead of data values).
• Suppose you want to give a prize to the winner.
• In such case you have two options:

a) Use the name of the winner- Ahmed (Call by value)


OR
b) Give this prize to the person sitting in row 5, seat NO. 8 (Call by Reference)
Location X

Address of X = 60000 X = 10
3
Declaring Pointers
Pointer Syntax
No space

int *myptr; // Read Right to Left


myptr is a pointer to an integer

Similarly

Double *x; // Pointing to double


Char *C; // Pointing to char

4
Assigning addresses to Pointers

Example:

int *ptr; // Pointer is a whole number big enough to store memory address
int x;

X = 10;

Ptr = &x; // Assigning the address of x to ptr

Now in order to read the value in that memory location, we use “star operator” that is

5
Dereferencing Operator *
*Ptr is read as the value of whatever ptr points to

Z = *ptr * 2;
Initializing Pointers:
Giving starting value to a Pointer that is
Ptr = &var;
Ptr = 0;
Ptr = NULL;

// Global constant declared in the header file (#include…)


0 and Null Points to nothing 6
Get Value of Thing Pointed by Pointers

int *pc, c;
c = 5;
pc = &c;

printf("%d", *pc); // Output: 5

Note: In the above example, pc is a pointer, not *pc. You


cannot and should not do something like *pc = &c;

7
Changing Value Pointed by Pointers

int *pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1

Note: We have assigned the address of c to the


pc pointer.
Then, we changed the value of c to 1. Since pc
and the address of c is the same, *pc gives us 1. 8
Declaring Pointers
int *ptr1, *ptr2, *ptr3; // More than one pointers on one line.
int *ptr, x;
int *ptr, x, a[10];

NOTE: the address operator “&” can not be used in an expression i.e;

&x+1, it can only be either &X OR &Y.

9
Example:
var: 5
#include <stdio.h> address of var: 2686778

int main()
{

int var = 5;
printf("var: %d\n", var); // Notice the use of & before var
You will probably get
a
printf("address of var: %p", &var); different address
when
return 0; you run the above
code.
}
10
Common mistakes when
working with pointers
Suppose, you want pointer pc to point to the address of c. Then,

int c, *pc;

// pc is address but c is not


pc = c; // Error

// &c is address but *pc is not


*pc = &c; // Error

// both &c and pc are addresses


pc = &c;

// both c and *pc are values 11


Examples

int *pc, c; We have assigned the address of c to the pc pointer.


c = 5;
pc = &c; Then, we changed *pc to 1 using *pc = 1;. Since pc and the
*pc = 1; address of c is the same, c will be equal to 1.
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1

int *pc, c, d;
c = 5;
d = -15;
Initially, the address of c is assigned to the pc pointer using
pc = &c; pc = &c;. Since c is 5, *pc gives us 5.
printf("%d", *pc); // Output: 5
pc = &d; Then, the address of d is assigned to the pc pointer using
printf("%d", *pc); // Ouptut: -15 pc = &d;. Since d is -15, *pc gives us -15.

12
Example
#include <stdio.h>
int main()
{
int *pc, c;

c = 22;

printf("Address of c: %p\n", &c);


printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
13
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2
14
Passing Pointer to a Function

When we pass a pointer as an argument instead of a variable then the


address of the variable is passed instead of the value. So any change made
by the function using the pointer is permanently made at the address of
passed variable.

Pointer as a function parameter is used to hold addresses of arguments


passed during function call. This is also known as call by reference. When a
function is called by reference any change made to the reference variable
will effect the original variable.

15
Passing Pointer to a Function

When we pass a pointer as an argument instead of a variable then the


address of the variable is passed instead of the value. So any change made
by the function using the pointer is permanently made at the address of
passed variable.

Pointer as a function parameter is used to hold addresses of arguments


passed during function call. This is also known as call by reference. When a
function is called by reference any change made to the reference variable
will effect the original variable.

16
Example Time: Swapping two numbers using Pointer
#include <stdio.h>
void swap(int *a, int *b);

int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);

swap(&m, &n); //passing address of m and n to the swap function

printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
} 17
Example Time: Swapping two numbers using Pointer

/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a; Output
*a = *b; m = 10
n = 20
*b = temp; After Swapping:
} m = 20
n = 10

18
Functions returning Pointer variables

A function can also return a pointer to the calling function. In this case you must
be careful, because local variables of function doesn't live outside the function.
They have scope only inside the function. Hence if you return a pointer
connected to a local variable, that pointer will be pointing to nothing when the
function ends.
#include <stdio.h>

int* larger(int*, int*);

void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b); 19
Functions returning Pointer variables

printf("%d is larger",*p);
}

int* larger(int *x, int *y)


{
if(*x > *y)
return x;
else OutPut
return y;
92 is larger
}

20
Safe Way to Return a valid Pointer

• Either use arguments with functions, Because argument passed to the


function are declared inside the calling function, hence they will live outside the
function as well.

• OR, use static local variables inside the function and return them. As static
variable has lifetime until the main() exists Therefore they will be available
through out the program.

21
Pointer to functions

It is possible to declare a pointer pointing to a function which can then be used as an


argument in another function. A pointer to a function is declared as follows,

type (*pointer-name)(parameter);

Example:

int (*sum)(); //legal declaration of pointer to function


int *sum(); //This is not a declaration of pointer to function
22
Pointer to functions

A function pointer can point to a specific function when it is assigned the


name of that function.

int sum(int, int);


int (*s)(int, int);
s = &sum;

Here s is a pointer to a function sum. Now sum can be called using function
pointer s along with providing the required argument values.

s (10, 20); 23
Example of Pointer to Function
#include <stdio.h>

int sum(int x, int y)


{
return x+y;
}

int main( )
{
int (*fp)(int, int);
fp = &sum;
int s = fp(10, 15);
printf("Sum is %d", s); OutPut
25
return 0;
}
24
Pointers and Arrays
Array:
An array is a group (or collection) of same data types. For example an int array holds the
elements of int types while a float array holds the elements of float types.
Why we need Array in C Programming?
Consider a scenario where you need to find out the average of 100 integer numbers
entered by user. In C, you have two ways to do this:
1) Define 100 variables with int data type and then perform 100 scanf() operations to
store the entered values in the variables and then at last calculate the average of them.
2) 2) Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
Which solution is better?
it is convenient to store same data types in one single variable and later access them using
array index.

25
Pointers and Arrays

int main()
{
Function_1(); // function call
printf(“this is the end of first function”);
Function_2(); // function call Run Example in Code Blocks
printf(“this is the end of second function”);
(function definitions are given
there)
Function_3(); // function call
printf(“this is the end of third function”);
Function_4(); // function call
printf(“this is the end of fourth function”);
return 0;
}
26
Pointers and Arrays
1. Function Prototype/Declaration
2. Function Definition
3. Function Call

27
Function Declaration or Prototype
• A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type.
• It gives information to the compiler that the function may later be
used in the program. Parameters List
Syntax:
returnType functionName (type1 argument1, type2 argument2, ...);
Example:

void display();
int addition (int a, int b);
28
Function Definition
It has two parts;
1. Function Header
• Function Name
• Function Type (return type)
int function_name (void)
• List of Parameters
• No semi-colon at the end { int x, y;
2. Function Body statements….
• Local Variable Declarations …..
• Function Statements return 0;
• A return Statement }
• All enclosed in curly braces
29
Pointers and Arrays
• It contains the function body.
• Function body is the block of code to perform a specific task.
Example: (A function to add two numbers)
int sum (int num1, int num2)
{
int result;
result = num1+num2;
/* Function return type is integer, so we are returning an integer value, the
result of the passed numbers. */
return result;
} 30
Pointers and Arrays
• A user-defined function is called from the main function.
• When a program calls a function, the program control is transferred to
the called function.
main() return_type funct_1()
{ {
……….. …………….
………… …………….
funct_1(); ……………..
………… …………………
………… }
}

Calling Function Called Function


(Boss Function) (Worker Function) 31
Pointers and Arrays
Any called function can call another function and control passes between those two functions
in hierarchical manner.

main ()

Called function in first level

Called function in second level

32
Pointers and Arrays
int sum(int , int );
• A function called void display(int);
int main()
inside main function {
can call another sum(4,5); // main is calling a user-defined function
function. return 0;
}
//__________________________________________________
• The control passes int sum(int a, int b) // Called Function in First Level by main
between the calling function
and called function { int y;
y=a+b;
at each level of
display(y); // sum is calling another function display()
hierarchy. return 0;
} //__________________________________________________
void display(int z) // Called function in second level by sum
function
{ 33
Array traversal using pointers
• Arguments are used to communicate between the calling and the
called function
//Function Declaration
With int sum (int a, int b);
Arguments // Function Call
sum(10,20);
Functions
//Function Declaration
Without int display();
Arguments // Call
display();
34
Array traversal using pointers
A function may or may not return a
result. But if it does, we must use the
return statement to output the result.
return statement also ends the
function execution.
return statement can occur anywhere
in the function depending on the
program flow.

35
Array traversal using pointers
Example:
Take two points from user that define a point location in 2D cartesian co-
ordinate. Write a C program using functions to convert this point location
to polar coordinates.
Solution:
Domain Knowledge: Mathematics
• To convert from Cartesian Coordinates to Polar Coordinates

36
Array traversal using pointers
int main()
{
float x,y, theta, r;
printf("Enter a number for x coordinate: \n");
scanf("%f", &x); float distance(float a, float b)
{ float d;
printf("Enter a number for y coordinate: \n");
/* Calculating r */
scanf("%f", &y);
d = sqrt(a*a + b*b);
r = distance(x,y); //calling function distance return d;
theta = angle(x,y); //calling function angle }
printf("The polar coordinates of %f and %f are; \n r = %f \n
theta = %f \n", x,y,r, theta);
return 0;
}

37
float angle(float a, float b)
Sorting and { float ang, m;
searching m=b/a;
ang= atan(m);
elements in /* Converting theta from radian to degrees */
printf("The angle in radians is %f\n", ang);
an array ang= ang * (180/ PI);
/* Conditional Check for Polar angle) */
if((a<0) && (b>0))
{ ang= 180 + ang;
return ang;
angle function in C: }
else if ((a>0) && (b<0))
{ ang = -ang;
return ang; }
else if ((a<0) && (b<0))
{ ang = 180 + ang;
return ang; }
else
return ang;
}
38
Sorting and searching elements in
an array
1) main() in C program is also a function.

2) A C program can have any number of functions, There is no limit on number


of functions. One of those functions must be a main function

3) Functions can be defined in any order

4) Function names in a program must be unique

5) A function gets called when the function name is followed by a semi-colon

6) A function cannot be defined inside a function.


39

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy