Download presentation
Presentation is loading. Please wait.
1
UNIT 5 POINTERS AND FILES
Noornilo Nafees
2
Pointers Pointer is a variable that contains the memory address of another variable. Advantages: It supports dynamic memory allocation and reallocation of memory segments. Variables can be swapped without physically moving them It reduces the length and complexity of the program Noornilo Nafees
3
Example: x=5 x Variable Address 5 Value Noornilo Nafees
4
Example #include<stdio.h> #include<conio.h> void main() {
int x=5; printf("\n The Address of x = %u",&x); printf("\n The Value of x = %d",x); } Output The Address of x = 8714 The Value of x = 5 Noornilo Nafees
5
Pointer Declaration Syntax data-type *pointer-name;
data-type - Type of the data to which the pointer points. pointer-name - Name of the pointer Example: int *a; Noornilo Nafees
6
Accessing Variable through Pointer
If a pointer is declared and assigned to a variable, then the variable can be accessed through the pointer. Example: int *a; int x=5; a=&x; Noornilo Nafees
7
Example #include<stdio.h> #include<conio.h> void main() {
int x=5; int *a; a=&x; printf("\n The Value of x = %d",*a); printf("\n The Address of x = %u",a); } Noornilo Nafees
8
Output The Value of x = 5 The Address of x = 8758 Noornilo Nafees
9
Example Output #include<stdio.h> #include<conio.h>
//Area of Circle #include<stdio.h> #include<conio.h> void main() { float r, area, pi=3.14; float *radius; radius=&r; printf(“Enter the radius : “); scanf(“%f”, &r); area=pi*(*radius)*(*radius); printf(“The area of circle is : %f”, area); getch(); } Output Enter the radius : 5.5 Area of circle is : Noornilo Nafees
10
DYNAMIC MEMORY ALLOCATION
It is a process by which the required memory address is obtained without an explicit declaration. The required memory space is obtained by using the memory allocation functions like malloc() and calloc(). malloc() function: Used to allocate a single block of memory to store values of specific data types. Syntax: ptr=(type *)malloc(size); ptr : Pointer variable type : Data type size : Number of bytes to be alloted Ex: int *ptr; ptr= (int *)malloc(20); The alloted space can be used to store 10 int type variables Noornilo Nafees
11
Example program for malloc() function: #include<stdio.h>
#include<malloc.h> #include<conio.h> void main() { float *fp; fp=(float *)malloc(10); printf(“Enter a float value : “); scanf(“%f”, &fp); printf(“The address of pointer in memory is : %u”, fp); printf(“The value stored in memory is : %f”, *fp); getch(); } Noornilo Nafees
12
ptr = (type *)calloc(n,m); ptr = Pointer variable type = Data type
calloc() function: It is used to allocate memory in multiple blocks of same size during program execution. Syntax: ptr = (type *)calloc(n,m); ptr = Pointer variable type = Data type n = Number of blocks to be allotted m = Number of bytes in each block of memory Ex: float *ptr; ptr=(float *)calloc(20,4) Noornilo Nafees
13
Example program for calloc() function: #include<stdio.h>
#include<calloc.h> #include<conio.h> void main() { float *fp; fp=(float *)calloc(10,4); printf(“Enter a float value : “); scanf(“%f”, &fp); printf(“The address of pointer in memory is : %u”, fp); printf(“The value stored in memory is : %f”, *fp); getch(); } Noornilo Nafees
14
Syntax: ptr=realloc(ptr,size); Ex: int *p; p=(int *)malloc(50);
realloc() function: It is used to modify or reallocate the memory space which is previously allocated. Syntax: ptr=realloc(ptr,size); Ex: int *p; p=(int *)malloc(50); p=realloc(p,100); //50 bytes is modified as 100 bytes. free() function: It is used to release the memory space which is allocated using malloc() or calloc() function Syntax: free(ptr); Noornilo Nafees
15
POINTER ARITHMETIC Arithmetic operation supported pointers are
Increment Decrement Adding integer value with pointer Subtracting integer value with pointer The following arithmetic operations are not allowed with pointers Multiplication Division Add or subtract float/double with pointers… Noornilo Nafees
16
Increment: int x, *p; p=&x; p++; p++ will not add 1 to p, but add size of that data type with p, which is pointed by the pointer If p is 1000(Addr of x) after the statement p=&x, then after p++, p will be 1002, because the size of x is 2 bytes Noornilo Nafees
17
If p1 is 1000(Addr of x) after the statement p1=&x then:
Decrement: int x, *p1,*p2,*p3; p1=&x; p2=p1--; p3=p1--; p1-- will not decrement 1 to p1, but subtract the size of that data type with p1, which is pointed by the pointer If p1 is 1000(Addr of x) after the statement p1=&x then: After the statement p2=p1--, p2=998 After the statement p3=p1--, p3=996 Noornilo Nafees
18
#include<stdio. h> #include<conio
#include<stdio.h> #include<conio.h> void main() { int x=100; int *ptr; ptr=&x; clrscr(); printf(“Address of x before increment = %u”,ptr); ptr++; printf (“Address of x after increment = %u”,ptr); printf (“Address of x before decrement = %u”,ptr); ptr--; printf(“Address of x after decrement = %u”,ptr); getch(); } //Program to display the memory address of a variable using pointers, before and after increment and decrement Noornilo Nafees
19
Adding integer value with pointer: int *p,x; x=10; p=&x; p=p+7;
If p is 1000(Addr of x), then after the statement p=p+7, p will be 1014. Subtracting integer value with pointer: p=p-7; If p is 1000(Addr of x), then after the statement p=p-7, p will be 986. Noornilo Nafees
20
//Program for adding and subtracting integer value with pointer
#include<stdio.h> #include<conio.h> void main() { int x, *p1, *p2, *p3; x=20; p1=&x; p2=p1+7; p3=p1-7; printf(“Value of p1=%d”, *p1); printf(“\nAddress of p1=%u”, p1); printf(“\nAddress of p2=% u”, p2); printf(“\nAddress of p3=% u”, p3); getch(); } //Program for adding and subtracting integer value with pointer Noornilo Nafees
21
FILES Files are places where data can be stored permanently.
In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Noornilo Nafees
22
Defining and opening file: In order to define and open file we need
Filename (e.g. sort.c, input.txt) Data structure (e.g. FILE) Purpose (e.g. Reading, Writing, Appending) Filename: String of characters that make up a valid file name. May contain two parts Primary Optional period with extension Examples: a.out, prog.c, temp, text.out Noornilo Nafees
23
The above statement declares that
Data Structure: FILE *fptr1, *fptr2 ; The above statement declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Noornilo Nafees
24
General format for opening file:
Purpose: General format for opening file: FILE *fp; /*variable fp is pointer to type FILE*/ fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns identifier to fp */ fp contains all information about file Communication link between system and program Various modes of operation on files r open file for reading only w open file for writing only a open file for appending (adding) data Noornilo Nafees
25
Various modes of operations on files: Writing mode
If the file already exists then contents are deleted, Else a new file with specified name is created Appending mode If the file already exists then the file is opened with contents and further updated. Else new file created Reading mode If the file already exists then it is opened with contents. Else error occurs. Ex: FILE *p1, *p2, *p3; p1 = fopen(“data”,”r”); p2= fopen(“results”, w”); p3= fopen(“results”, a”); Noornilo Nafees
26
File must be closed as soon as all operations on it completed. Ensures
Closing a File: File must be closed as soon as all operations on it completed. Ensures All outstanding information associated with file flushed out from buffers All links to file broken If we want to change mode of file, then first close and then open again. Syntax: fclose(file_pointer); Example: FILE *p1, *p2; p1 = fopen(“INPUT.txt”, “r”); p2 =fopen(“OUTPUT.txt”, “w”); …….. fclose(p1); fclose(p2); Noornilo Nafees
27
Input and Output Operations with Files:
C provides several different functions for reading/writing in to files. Some of them are getc() – read a character putc() – write a character fprintf() – write set of data values fscanf() – read set of data values Noornilo Nafees
28
This function handles one character at a time. Syntax: putc(c,fp1);
getc() and putc(): This function handles one character at a time. Syntax: putc(c,fp1); c : a character variable fp1 : pointer to file opened with mode w Syntax: c = getc(fp2); fp2 : pointer to file opened with mode r File pointer moves by one character position after every getc() and putc() getc() returns end-of-file marker EOF when file end reached Noornilo Nafees
29
//Program for file manipulation using getc() and putc();
#include <stdio.h> void main() { FILE *fp1; char c; f1= fopen(“INPUT”, “w”); /* open file for writing */ while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/ putc(c,f1); /*write a character to INPUT */ fclose(f1); /* close INPUT */ f1=fopen(“INPUT”, “r”); /* reopen file */ while((c=getc(f1))!=EOF) /*read character from file INPUT*/ printf(“%c”, c);/* print character to screen */ fclose(f1); } //Program for file manipulation using getc() and putc(); Noornilo Nafees
30
fprintf() and fscanf(): Syntax of fprintf():
fprintf(FILE *fp,"format-string",var-list); Syntax of fscanf(): fscanf(FILE *fp,"format-string",var-list); Noornilo Nafees
31
#include<stdio. h> void main() { FILE
#include<stdio.h> void main() { FILE *fp; int roll; char name[25]; float marks; char ch; fp = fopen("file.txt","w"); //Statement 1 if(fp == NULL) printf("\nCan't open file or file doesn't exist."); exit(0); } //Program for file manipulation using fprintf() Noornilo Nafees
32
do { printf("\nEnter Roll : "); scanf("%d",&roll); printf("\nEnter Name : "); scanf("%s",name); printf("\nEnter Marks : "); scanf("%f",&marks); fprintf(fp,"%d%s%f",roll,name,marks); printf("\nDo you want to add another data (y/n) : "); ch = getche(); }while(ch=='y' || ch=='Y'); printf("\nData written successfully..."); fclose(fp); } Noornilo Nafees
33
Output : Enter Roll : 1 Enter Name : Nilo Enter Marks : 78
Output : Enter Roll : 1 Enter Name : Nilo Enter Marks : Do you want to add another data (y/n) : y Enter Roll : 2 Enter Name : Nafees Enter Marks : Do you want to add another data (y/n) : n Data written successfully... Noornilo Nafees
34
#include<stdio. h> void main() { FILE
#include<stdio.h> void main() { FILE *fp; char ch; fp = fopen("file.txt","r"); //Statement 1 if(fp == NULL) printf("\nCan't open file or file doesn't exist."); exit(0); } //Program for file manipulation using fscanf() Noornilo Nafees
35
printf("\nData in file...\n"); while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF) //Statement 2 { printf("\n%d\t%s\t%f",roll,name,marks); } fclose(fp); Output : Data in file... 1 Nilo Nafees 89.62 Noornilo Nafees
36
Preprocessor It is a program that processes the source program before compilation. It operates under the following directives File Inclusion Macro substitution Conditional inclusion Noornilo Nafees
37
File Inclusion It is used to include some file that contains functions or some definitions. Syntax: #include<filename> (or) #include“filename” Eg: #include<stdio.h> #include “ex.c” Noornilo Nafees
38
Example #include<stdio.h> #include<conio.h>
#include "addition.txt" void main() { int a,b; printf("\nEnter the numbers:"); scanf("%d%d",&a,&b); printf("The Value is %d",add(a,b)); getch(); } Noornilo Nafees
39
addition.txt int add(int a,int b) { return(a+b); } Noornilo Nafees
40
Output Enter the numbers:7 4 The Value is 11 Noornilo Nafees
41
Example #include<stdio.h> #include<conio.h>
#include "fact.c" void main() { int a; printf("\nEnter the number:"); scanf("%d",&a); printf("The factorial of %d! is %d",a,rec(a)); getch(); } Noornilo Nafees
42
Macro Substitution It is used to define and use integer, string, or identifier in the source program The three forms of macros are Simple Macro Argumented Macro Nested Macro Noornilo Nafees
43
Simple Macro It is used to define some constants Syntax
# define identifier string/integer Eg: #define pi 3.14 #define CITY “chennai” Noornilo Nafees
44
Example #include<stdio.h> #include<conio.h>
#define pi 3.14 #define CITY "chennai" void main() { printf("The Value is %f",2*pi); printf("\nThe Value CITY is %s",CITY); getch(); } Output: The Value is The Value CITY is chennai Noornilo Nafees
45
Argumented Macro It is used to define some complex forms in the source program. Syntax: #define identifier (v1,v2,….) string/integer Eg: #define cube(n) (n*n*n) Noornilo Nafees
46
Example #include<stdio.h> #include<conio.h>
#define cube(n) (n*n*n) void main() { printf("The Value of 3 cube is %d",cube(3)); getch(); } Output: The Value of 3 cube is 27 Noornilo Nafees
47
Nested Macro Here one macro is used by another macro. Eg: #define a 3
#define sq a*a Noornilo Nafees
48
Example #include<stdio.h> #include<conio.h> #define a 3
#define sq a*a void main() { printf("The Value is %d",sq); getch(); } Output: The Value is 9 Noornilo Nafees
49
Conditional Inclusion
It is used to include some conditional statements. Noornilo Nafees
50
Example #include<stdio.h> #include<conio.h> #define a 3
#ifdef a #define c a+5 #endif void main() { printf("\nThe value C is %d",c); getch(); } Output: The value C is 8 Noornilo Nafees
51
Storage classes Every C variable has a storage class,
Storage classes determines : The part of memory where storage is allocated for variable What will be the initial value of the variable if not assigned How long the storage allocation continues to exists. The scope which specifies the part of the program over which a variable name is visible Categories of storage classes in C: Automatic External Static Register Noornilo Nafees
52
Automatic (auto) Output 30 20 10
By default, variables in C uses the auto storage class. The variables are automatically created when needed and deleted when they fall out of the scope. Ex: void main() { auto int a=10; auto int a=20; auto int a =30; printf(“%d”,a); } printf(“\n%d”,a); Output 30 20 10 Noornilo Nafees
53
Automatic (auto) Storage : Memory
Scope : Within the block in which variable is defined Life : Till the program control is within the block Default value : Un predictable (Garbage Value) Noornilo Nafees
54
External (Global) -extern
Global variables are accessible from within any block & or remains in existence for the entire execution of the program. Using global variables we can transfer information into a function without using arguments Ex: void sum(); int a=10,b=5; void main() { clrscr(); sum(); getch(); } void sum() int c; c=a+b; printf(“Added values : %d”,c); Output Added values : 15 Noornilo Nafees
55
External - extern Storage : Memory Scope : Global
Life : During entire program execution Default value : zer0 Noornilo Nafees
56
Static variables - static
Storage: Memory Scope : Local to the block in which the variable is defined Life : Value of the variables persist between different function calls Default value : zer0 Ex: void incr(); void main() { incr(); } void incr() static int a=1; printf(“%d\t”,a); a=a+1; Output 1 2 3 Noornilo Nafees
57
Register variables - register
Register variables are usually stored in memory and passed back & forth to the processor as needed. Storage: CPU Registers Scope : Local to the block in which the variable is defined Life : Till the program control is within the block in which variable is defined. Default value : Unpredictable(Garbage). Ex: void main() { register int counter; } Noornilo Nafees
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.