Advanced pointers

  • View
    67

  • Download
    0

  • Category

    Design

Preview:

Citation preview

Pointers

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.

#include<stdio.h>

int main()

{

int a = 3;

int *ptr,**pptr;

ptr = &a;

pptr = &ptr;

return(0);

}

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.

Declaring Pointer Variables

int n = 20;

int *ptr;

char ch = 'A';

char *cptr;

float fvar = 3.14;

float *fptr;

● int *x;

● int **y;

● double *z;

x some int

some *int some int

some double

y

z

Applications of Pointers

Passing Parameter by Reference Accessing Array element Dynamic Memory Allocation Reducing size of parameter

Passing parameters by reference

void interchange(int *num1,int *num2)

{

int temp;

temp = *num1;

*num1 = *num2;

*num2 = temp;

}

Accessing array elementsint 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);

}

Dynamic memory allocationWe 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 = %u\n", str, str);

free(str);

return(0);

}

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

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;

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.

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

Dereferencing Void Pointers

Type of Address Stored in Void Pointer

Dereferencing Void Pointer

Integer *((int*)ptr)

Character *((char*)ptr)

Floating *((float*)ptr)

#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);

}

Double Pointer

Pointer to Pointer in C Programming.

int num = 45 , *ptr , **ptr2ptr ;

ptr = &num;

ptr2ptr = &ptr;

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.

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

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 ;

Functions

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.

Advantages

Modular Programming Length of source program can be reduced

Easy to locate and isolate faulty function

Functions can be used by other program’s

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.

Elements of User defined functions

Function Prototype

Function Call

Function arguments and parameters

Function Definitions

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);

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);

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.

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.

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

Function with no argument and no return

Function with argument and no return

Function with no argument and return

Function with argument and return

Methods of calling function

● Call by value● Call by reference

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.

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.

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.

Example#include<stdio.h>

void display();

int main() {

void (*ptr)();

ptr = display;

(*ptr)();

return(0);

}

void display(){

printf("Hello World");

}

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);

}

Accessing Integer using Character

#include<stdio.h>

int main() {

int a=320;

char *ptr;

ptr=(char *)&a;

printf("%d",*ptr);

return(0);

}

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.

Example1

#include<stdio.h>

void fun1()

{

printf("hai");

}

void fun2()

{

printf("hello");

}

void fun3()

{

printf("bye");

}

void (*func_ptr[3])()= {fun1, fun2, fun3};int main(){ int i; scanf("%d",&i); if((i>=0)&&(i<=2)) { (*func_ptr[i])(); } return 0;}

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 : %d\n", a, b,(*functionptr[0])(a, b));

printf("Difference of %d and %d : %d\n", a, b,(*functionptr[1])(a, b));

printf("Product of %d and %d : %d\n", a, b,(*functionptr[2])(a, b));

printf("Division of %d and %d : %d\n", a, b,(*functionptr[3])(a, b));

}

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;

}

Pointers to Structures

Pointers can be accessed along with structures.

struct name

{

int a;

float b;

.

.

};

-------- Inside function -------

struct name *ptr;

The accessing of these structure members are given by

(*ptr).a (*ptr).bStructure pointer member can also be accessed

using -> operator. (*ptr).a is same as ptr->a. (*ptr).b is same as ptr->b.

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 %d\n", x.a, x.b, x.c);}

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.

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; }

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.

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.

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

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.

Example1#include<stdio.h>

int main(int argc,char *argv[])

{

int i;

for(i=1;i<argc;i++)

{

printf(“%s”,argv[i]);

}

return 0;

}

Example2#include<stdio.h>

#include<stdlib.h>

int main(int argc,char *argv[])

{

int i;

for(i=1;i<argc;i++)

{

printf(“%d”,atoi(argv[i]));

}

return 0;

}

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]

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]

Example

#include <stdio.h>

int main(void)

{

char a[] = "pascual";

char *p = a;

p += 3;

printf("%c\n", p[-1]); /* -1 is valid here? */

return 0;

}

Recommended