2. Introduction to pointers
Pointer is Special Variable used to
Reference and de-reference memory.
When we declare integer pointer then we
can only store address of integer variable
into that pointer.
Similarly if we declare character pointer
then only the address of character
variable is stored into the pointer
variable.
4. Memory required to store Pointer
Pointer Variable Stores the address of
the variable.
Variable may be integer , character ,
float but the address of the variable is
always integer so Pointer requires 4
bytes of memory.
9. Accessing array elements
int main(){
int a[5] = {1,2,3,4,5};
int *ptr;
ptr = a; //storing base address of array in pointer.
//accessing each and individual location using pointer.
for(i=0;i<5;i++) {
printf("%d",*(ptr+i));
}
return(0);
}
10. Dynamic memory allocation
We can use pointer to allocate memory dynamically. Malloc and calloc
function is used to allocate memory dynamically.
#include <stdio.h>
#include <stdlib.h>
int main(){
char *str;
str = (char *) malloc(15);
strcpy(str, "mahesh");
printf("String = %s, Address = %un", str, str);
free(str);
return(0);
}
11. Operations on Pointers
●
Can be done, Valid Operations
– Addition/Subtraction of a number to/from pointer
– Subtraction of two pointers
– Comparison of two pointers
– Assignment of a pointer to another pointer
●
Can NOT be done, Invalid Operations
– Addition of two pointers
– Multiplication/Division of a pointer with a number
12. Pointer arithmetic
●
Integer math operations can be used with pointers.
●
If you increment a pointer, it will be increased by the size
of whatever it points to.
●
You can use the integer x points to in a C expression
like this:
y = *x + 17;
*x = *x +1;
13. Void Pointers
In C General Purpose Pointer is called as void
Pointer.
It does not have any data type associated with
it.
It can store address of any type of variable.
The compiler has no idea what type of object
a void Pointer really points to.
14. Void Pointer Example
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
15. Dereferencing Void Pointers
Type of Address Stored
in Void Pointer
Dereferencing Void Pointer
Integer *((int*)ptr)
Character *((char*)ptr)
Floating *((float*)ptr)
16. #include<stdio.h>
int main() {
int inum = 8;
float fnum = 67.7;
void *ptr;
ptr = &inum;
printf("nThe value of inum = %d",*((int*)ptr));
ptr = &fnum;
printf("nThe value of fnum = %f",*((float*)ptr));
return(0);
}
17. Double Pointer
Pointer to Pointer in C Programming.
int num = 45 , *ptr , **ptr2ptr ;
ptr = #
ptr2ptr = &ptr;
18. Pointer to Constant Objects
●
Pointer to a Constant Object is called as ‘Pointer to
Constant Object’.
int n = 30 ;
const int ptr;
ptr = &n;
●
“const int” means integer is constant.
●
We cannot change value of the integer.
●
We can change address of such pointer so that it
will point to new memory location.
19. Constant Pointers
●
As name suggests , Constant Pointers Cannot be
modified .
●
Modification in Integer to which it Points to is
Allowed.
int num = 20;
int * const ptr = &num ; // Declare Constant
pointer
*ptr = 20 ; // Valid Statement
ptr ++ ; // Invalid Statement
20. No Pointer to constant Constant Pointers
1 *ptr = 20 Statement is Invalid in
Pointer to Constant i.e Assigning Value
is Illegal
*ptr = 20 is Absolutely Valid in
Constant Pointers i.e Assigning Value
is Perfectly legal
2 ptr ++ Statement is Valid in Pointer to
Constant
ptr ++ Statement is invalid in
Constant Pointers
3 Pointer Can be Incremented and
Decremented
Pointer Cannot be Incremented and
Decremented
4 Pointer is Pointing to Constant Data
Object
Constant Pointer is Pointing to Data
Objects
5 Declaration : const int *ptr ; Declaration : int * const ptr ;
22. Introduction to Function
Block of statements that perform the particular
task.
Enables modular programming.
Has pre defined prototype.
Same function can be accessed from different
places within a program.
Once a function execution is completed , control
return to the place from where the function was
called.
24. Types of Functions
Library (Built In) Functions:
They are written in the header files.
To use them appropriate header files should be included.
User Defined Functions
Written by the user at the time of programming.
25. Elements of User defined functions
Function Prototype
Function Call
Function arguments and parameters
Function Definitions
26. Function prototype
It specify the type of value that is to be return from
the function and that is to be passed to the function.
It is defined in the beginning before the function
call is made.
Syntax:
return-type name-of-function(list of arguments);
Example
Void sum(int, int);
27. Function Call
A function can be called by specifying name and
list of arguments enclosed in parenthesis and
separated by comma.
If there is no arguments empty parenthesis are place
after function name.
If function return a value, function call is written as
assignment statement as:
A=sum(x,y);
28. Function arguments and parameters
Arguments are also called actual parameters.
Arguments are written within parenthesis at the
time of function call.
Parameters are also called formal parameters.
These are written within parenthesis at the time of
function definition.
29. Function Definition
It is the independent program module.
It is written to specify the particular task that
is to be performed by the function.
The first line of the function is called function
declarator and rest line inside { } is called
function body.
31. Categories of function
Function with no arguments and no return
Function with arguments but no return
Function with no arguments and return
Function with arguments and return
37. Call by value
Copies the value of actual parameters into
formal parameters.
During execution whatever changes are made
in the formal parameters are not reflected
back in the actual parameters.
38.
39. Call by Reference
Reference(address) of the original variable is
passed.
Function does not create its own copy, it
refers to the original values by reference.
Functions works with the original data and
changes are made in the original data.
40.
41. Function Pointers
●
A pointer which keeps address of a function is
known as function pointer.
●
int (*f)()
●
This is a pointer to a function. The name of the
pointer is 'f'. But the function it points to could be
any function that takes no parameters and returns
an int.
43. Addition of 2 numbers using function pointers
#include<stdio.h>
int sum (int n1,int n2);
int main() {
int num1 = 10;
int num2 = 20;
int result;
int (*ptr)(int,int);
ptr = sum;
result = (*ptr)(num1,num2);
printf("Addition : %d",result);
return(0);
}
int sum (int n1,int n2){
return(n1 + n2);
}
44. Accessing Integer using Character
#include<stdio.h>
int main() {
int a=320;
char *ptr;
ptr=(char *)&a;
printf("%d",*ptr);
return(0);
}
45. Array of function pointers
An array of function pointers can be created
for the functions of same return type and
taking same type and same number of
arguments.
47. void (*func_ptr[3])()= {fun1, fun2, fun3};
int main()
{
int i;
scanf("%d",&i);
if((i>=0)&&(i<=2))
{
(*func_ptr[i])();
}
return 0;
}
48. Example2
#include <stdio.h>
int getSum(int, int);
int getDifference(int, int);
int getProduct(int, int);
int getDivision(int, int);
int (*functionptr[4])(int, int) = {getSum, getDifference, getProduct, getDivision};
int main()
{
int a = 50, b = 20;
printf("Sum of %d and %d : %dn", a, b,(*functionptr[0])(a, b));
printf("Difference of %d and %d : %dn", a, b,(*functionptr[1])(a, b));
printf("Product of %d and %d : %dn", a, b,(*functionptr[2])(a, b));
printf("Division of %d and %d : %dn", a, b,(*functionptr[3])(a, b));
}
49. int getSum(int x, int y)
{
return x + y;
}
int getDifference(int x, int y)
{
return x - y;
}
int getProduct(int x, int y)
{
return x * y;
}
int getDivision(int x, int y)
{
return x / y;
}
50. Pointers to Structures
Pointers can be accessed along with structures.
struct name
{
int a;
float b;
.
.
};
-------- Inside function -------
struct name *ptr;
51. The accessing of these structure members are given
by
(*ptr).a
(*ptr).b
Structure pointer member can also be accessed
using -> operator.
(*ptr).a is same as ptr->a.
(*ptr).b is same as ptr->b.
52. Example
#include <stdio.h>
struct foo {
int a, b, c;
};
void inp(struct foo *);
void outp(struct foo);
void main( ) {
struct foo x;// declare x to be a foo
inp(&x); // get its input, passing a pointer to foo
outp(x); // send x to outp, this requires 2 copying actions
}
void inp(struct foo *x)
{
scanf("%d%d%d", &x->a, &x->b, &x->c);
}
void outp(struct foo x) {
printf("%d %d %dn", x.a, x.b, x.c);
}
53. Linked Structures
These are dynamic structures, when you want to
add a node, you allocate a new chunk of memory
and attach it to the proper place in the structure via
the pointers.
Each node in the structure will have at least one
datum and at least one pointer.
In linked lists, the pointer is a next pointer to the
next node in the list, in a tree, there are left and
right children pointers.
54. Declarations for Nodes
struct node {
int data;
struct node *next;
};
node *front;
front is a pointer to the first node in a linked list. It may
initially be NULL. Traversing our linked list might use
code like this:
temp = front;
while(temp!=NULL)
{
// process temp
temp=temp->next;
}
55. Command line arguments
Command line arguments are a way of providing
input to a program.
Many real-world unix programs use command line
arguments rather than printf/scanf to get their
input.
The user of the program types the input to the
program after the name of the program on the
command line.
56.
main() function of a C program accepts arguments
from command line by following commands. They
are,
argc
argv[]
int main(int argc, char *argv[])
argc is a variable that indicates the number of
things on the command line.
argv is an array of the arguments.
57.
when we compile a program (test.c), we get executable file with
the name “test”.
Now, we run the executable “test” along with 4 arguments in
command line like,
./test this is a program
Where,
argc = 5
argv[0] = “test”
argv[1] = “this”
argv[2] = “is”
argv[3] = “a”
argv[4] = “program”
argv[5] = NULL
58. Conventional rules:
Arguments are always passed to main( ).
There must be two
first is an integer
second char pointer to an array
First argument (argv[0]) will always be the name of the
calling program.
argc will always be at least 1
The first argument is always argv[0]
The last argument is always argv[argc-1]
argv[argc] will always be a null pointer
Arguments are always passed as character strings.
Numbers must be converted from characters to integers,
floats, doubles, etc.
61. Arrays with negative indexes
| a | b | c | d | e | f | g |
^------------ arr[3]
^----------------arr[2]
^------------------ arr[1]
^---------------------- arr[0]
^------------------------- arr[-1]
^------------------------------ arr[-2]
^---------------------------------- arr[-3]
62. int arr[10];
int x = arr[-2]; // invalid; out of range
●
Arrays with negative indices is possible when
a pointer points to the elements of an array.
int arr[10];
int* p = &arr[2];
int x = p[-2]; // valid: accesses arr[0]