pointers

24
Pointers Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type like char, int, float, double or user defined data type like function, pointer etc. or derived data type like array, structure, union, enum. Examples: int *ptr; int (*ptr)(); int (*ptr)[2]; In c programming every variable keeps two type of value. 1. Contain of variable or value of variable. 2. Address of variable where it has stored in the memory. (1) Meaning of following simple pointer declaration and definition: int a=5;

Upload: iola-pratt

Post on 30-Dec-2015

25 views

Category:

Documents


0 download

DESCRIPTION

Pointers Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type like char, int, float, double or user defined data type like function, pointer etc. or derived data type like array, structure, union, enum. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pointers

Pointers

Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type like char, int, float, double or user defined data type like function, pointer etc. or derived data type like array, structure, union, enum.Examples: int *ptr;

int (*ptr)();

int (*ptr)[2];

In c programming every variable keeps two type of value.

1. Contain of variable or value of variable.

2. Address of variable where it has stored in the memory.(1) Meaning of following simple pointer declaration and definition:

int a=5;

int * ptr;

ptr=&a;

Page 2: Pointers

Explanation:

About variable a:

1. Name of variable : a

2. Value of variable which it keeps: 5

3. Address where it has stored in memory : 1025 (assume)

About variable ptr:4. Name of variable : ptr

5. Value of variable which it keeps: 1025

6. Address where it has stored in memory : 5000 (assume)

Note: A variable where it will be stored in memory is decided by operating system. We cannot guess at which location a particular variable will be stored in memory.

Page 3: Pointers

Pictorial representation:

Page 4: Pointers

Example:#include<stdio.h> #include<conio.h> void main() {     int i=9;     clrscr();       printf("Value of i : %d\n",i);     printf("Address of i : %u\n",&i);     printf("Value at address of i : %d",*(&i));     getch(); }Output:The values of i:9Address of i:65524Value at address of i:9

Page 5: Pointers

Passing pointers to function:

•C provides a special feature of  pointer to a function. Every function defined in C language have a base address attached to it. This base address acts as an entering point into that function.

•This address can be stored in a pointer known as function pointer. The pointer to a function is the declaration of pointer that holds the base address of the function.

Syntax :return_type (* pointer_name) ( variable1_type variable1_name  , variable2_type variable2_name , variable3_type variable3_name .................);  

Page 6: Pointers

Example:

int (*function_pointer) (int,int,int); 

Program Coding:#include <stdio.h>

#include <conio.h>

int mul(int a, int b, int c) 

{  return a*b*c;

}

void main() 

{  int (*function_pointer)(int, int, int);  function_pointer = mul;  printf("The product of three numbers is:%d",  function_pointer(2, 3, 4));  getch();

}

Output:

The product of three numbers is:24

Page 7: Pointers

Operations in Pointers

Eight basic operations that can be performed with pointer variables. In addition to these operations, you can use the relational

operators to compare pointers. •pointer reference by an arithmetic operation. For example:

int x = 5, *ip = &x;

ip++;

Array of Pointers

A pointer is a variable that contains the memory location of another variable. The values you assign to the pointers are memory addresses of other variables (or other pointers). A running program gets a certain space in the main memory.

Syntax of declaring a pointer:  data_type_name * variable name;

Page 8: Pointers

Pointer Operators-& and * C provides two special operators known as pointer operators. They are & and *.They are & and *.& stands for ‘Address of’ and it is used to retrieve the address of a variable.* stands for ‘value at address’ and it is used to access the value at a location by means of its address.Syntax data-type * variable-name;Example int *ip; where,ip is declared to be a pointer variable of int typeExample#include<stdio.h>#include<conio.h>void main(){ int i=10,*ip;

Page 9: Pointers

float f=3.4 *fp;

char c=‘a’ *cp; clrscr(); printf(“i=%d \n,i); printf(“f=%f \n,f); printf(“c=%c” \n”,c); ip=&i; printf(“\n Address of i=%u \n”,ip); printf(“Value of i=%d \n”,*ip); fp=*f; printf(“\n Address of f=%u \n,fp); printf(“Value of f=%f \n”,*fp); cp=&c; printf(“\n Address of c=%u \n”,cp); printf(“Value of c=%c \n”,*cp); getch();}

Page 10: Pointers

Pointers and Arrays

Elements of an array are accessed through pointers internally.

1.Pointers and One-Dimensional Arrays

Consider one-dimensional arrays and pointers. Suppose a is a one-dimensional array of int type and of size 10.

int a[10];

Since a is the address of a[0],*a is the element stored in the first location.(a+1) gives the address of the second element a[1] of the array.*(a+1) gives the element itself stored at a[1].Similary,(a+2) is the address of a[2] and *a(a+2) is the value at a[2].For Ex:

*a=*(a+0)=a[0]

=*(a+1)=a[1]

=*(a+2)=a[2]

=*(a+3)=a[3]

…………….

=*(a+i)=a[i]

Page 11: Pointers

#include<stdio.h>

void main()

{

int a[10],n,I;

clrscr();

printf(“Enter no. of elements \n”);

scanf(“%d”,&n);

printf(“Enter %d elements \n”,n);

for(i=0;i<n;i++)

scanf(“%d”,a+i);

printf(“The list if elements \n”);

for(i=0;i<n;i++)

printf(“%d \n”,*(a+i));

getch();

}

Enter no. of elements

5

Enter 5 elements

1 2 3 4 5

The list of items

1 2 3 4 5

Page 12: Pointers

Pointers and Two-dimensional Arrays

a is an array of two dimensions of int type,which is declared as:

int a[2][3];

The array name a gives its base address,i.e., the address of its first element.

For example,

*(*(a+1)+0) gives the first element in the 1st array a[0][0]

*(*(a+1)+1) gives the first element in the 1st array a[0][1]

*(*(a+1)+2) gives the first element in the 1st array a[0][2]

In general,a[i][j] can be written as *(*(a+i)+j)

Page 13: Pointers

Example:

#include<stdio.h>

#include<conio.h>

void main()

{

int a[3][3],m,n,I,j;

clrscr();

printf(“Enter the order of the matrix a \n”);

scanf(“%d%d”,&m,&n);

printf(“Enter elements of the matrix a of order %d %d \n”,m,n);

for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf(“%d”,*(a+i)+j);

printf(“Matrix a \n”);

for(i=0;i<m;i++)

{

for(j=0;j<n;j++)

printf(“%4d”,*(a(a+1)+j));

printf(“\n”);

}

getch();

}

Output

Enter the order of the matrix a

2 2

Enter elements of the matrix a of order 2*2

1 2 3 4

Matrix a

1 2

3 4

Page 14: Pointers

Arrays of Pointers• Specify the data type of data stored in the location, which is to identified by the

pointer. The asterisk tells the compiler that you are creating a pointer variable. Then specify the name of variable.

• we have created an array of pointers of maximum size 3. Then we have assigned the objects of array pointer.

• The address of the variable. array[0] = &x;array[1] = &y;array[2] = &z; Here is the code:

Page 15: Pointers

Examplevoid main() {

  clrscr();  int *array[3];  int x = 10, y = 20, z = 30;  int i;  array[0] = &x;  array[1] = &y;  array[2] = &z;  for (i=0; i< 3; i++) {  printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),  array[i]);  }  getch(); }

Page 16: Pointers

Pointers and Structure

The concept of pointers can be used in two ways:

1.Address of a structure variable can be retrieved using & operator.

2.We use & operator to retrieve the address of a structure variable.

Example

struct temp

{

int i;

float f;

char c;

}struct temp t,*tp;

Where,

t is declared to be variable of struct temp type.tp is declared to be a pointer to struct temp type.

Page 17: Pointers

Example:

#include<stdio.h>

#include<conio.h>

struct temp

{

int i;

float f;

char c;

};

void main()

{

struct temp t={123,34.56,’p’},*tp;

clrscr();

tp=&t;

printf(“t.i=%d \n”,tp->i);

printf(“t.f=%f \n”,tp->f);

printf(“t.c=%c \n”,tp->c);

getch();

}

Page 18: Pointers

Structures containing Pointersstruct temp{ int i; int *ip;}; The structure definition includes ip,a pointer to int type as one of its members.

Example#include<stdio.h>#include<conio..h>Struct temp{ int i; int *ip;};void main(){ struct temp t; int a=10; clrscr(); t.i=a; t.ip=&a; printf(“Value of a=%d”,t.i); printf(“Address of a=%u \n”,t.ip); getch();}Output:Value of a=10Address of a=65520

Page 19: Pointers

Files

•Files can be classified into many types depending upon the contents of the file.

Key terms used in file processing:

Field:A field is an elementary data item that is used to store a single unit of data.

Example:name

Record: A group of related fields constitute a record.

Example:rollnumber,name,mark1,etc.

File:A group of related records form a file.Generally,this type of file is called a data file.

Example:Employee data file

Stream:Input and output operations are performed through streams. In C files are streams of characters.The stream of characters are decoded by various Input and output functions like scanf(),getc(),etc.

Page 20: Pointers

Types of streams:

There are two types of streams:text and binary

text and binary:A text stream consists of ASCII characters. A binary stream consists of any type of data. The major difference between two stream permits character translation while transporting data.

Opening and/or Saving FilesTo create a new file, open an existing file, or save a file, you use the fopen() function:

Syntax:

FILE *fopen(const char *FileName, const char *Mode);

Where,

The fopen() function requires two arguments. The first argument ‘filename’ refers to the name of he file to be opened. The second argument ‘mode’ refers to the file mode, which specifies the purpose for which the file is opened.

Page 21: Pointers

Example:

fp=open(“salary.txt”,”w”);

if(fp=NULL)

{

printf(“\n Unable to open file.. Quitting process..\n”);

getch();

exit(0);

}

Page 22: Pointers

The following table illustrates the different modes of file operation:

File Type Meaning

“r” Opens an existing file for reading.

“w” Opens a new file for writing.

“a” Opens an existing file for appending.

“rb” Opens a binary file for reading.

“wb” Creates and opens a new binary file for writing.

“ab” Opes a binary file for appending

“r+” Opens fn existing file for reading and writing

“w+” Creates and opens a new file for reading and writing.

“a+” Open an existing file for reading and writing in the append mode.

“r+b” or “rb+” Opens a binary file for read and write operations

“w+b” or “wb+” Creates and opens a binary file for read and write operations

“a+b” or “ab+” Opens a binary for for read and write operations.

Page 23: Pointers

For example, consider the statements:

FILE *fp1,*fp2;

……..

……..

fp1=fopen(“emp.dat”,”r”);

fp2=fopen(“salary.txt”,”w”);

Closing a file

A file is closed when all the input/output operations are completed on it. The fclose is used to close an opened file.

Syntax:

int fclose(FILE *fp);

Where,

The file pointer fp is closed.

Page 24: Pointers

Operations on FilesThe following are various functions that are used on files.1.putc() function: This function is similar to the putchar().Syntax:

int putc(int ch,FILE *fp);2.getc() function:This function is similar to the getchar() function.Syntax:

int getc(int ch,FILE *fp);3.putw() function:This function is used to write an integer value onto the file pointed by the pointer.Syntax:

int putc(int w,FILE *fp);4.fprintf() function:This function is similar to the scanf() function.Syntax:

int fprintf(FILE *fp,format specifications,list of variables);5.fscanf() function:This function is similar to the scanf() function.Syntax:

int fscanf(FILE *fp,format specifications,list of variables);6.fread() function:This function reads data from stream file or file of any data type using binary representation..Syntax:

size_t fread(void *ptr,size_t size,size_t n,FILE *fp);7.fwrite() function:This function writes to a stream or specified file.Syntax:

size_t fwrite(const void *ptr,size_t size_t n,FILE *fp);