Pointers in C
Pointers in C
Lecture
Address of X = 60000 X = 10
3
Declaring Pointers
Pointer Syntax
No space
Similarly
4
Assigning addresses to Pointers
Example:
int *ptr; // Pointer is a whole number big enough to store memory address
int x;
X = 10;
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;
int *pc, c;
c = 5;
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: the address operator “&” can not be used in an expression i.e;
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;
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;
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 c: 2686784
Value of c: 2
14
Passing Pointer to a Function
15
Passing Pointer to a Function
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);
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>
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b); 19
Functions returning Pointer variables
printf("%d is larger",*p);
}
20
Safe Way to Return a valid Pointer
• 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
type (*pointer-name)(parameter);
Example:
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 main( )
{
int (*fp)(int, int);
fp = ∑
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(); ……………..
………… …………………
………… }
}
main ()
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.