0% found this document useful (0 votes)
54 views

Chapter 1 OOP

This document provides a summary of pointers in C programming. It discusses: 1) Declaring and initializing pointers, dereferencing pointers, and NULL pointers. 2) Pointer arithmetic operations like incrementing, decrementing, adding, and subtracting values from pointers. 3) Dynamic memory allocation functions like malloc(), calloc(), and realloc() to allocate and manage memory during runtime.

Uploaded by

Vansh Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Chapter 1 OOP

This document provides a summary of pointers in C programming. It discusses: 1) Declaring and initializing pointers, dereferencing pointers, and NULL pointers. 2) Pointer arithmetic operations like incrementing, decrementing, adding, and subtracting values from pointers. 3) Dynamic memory allocation functions like malloc(), calloc(), and realloc() to allocate and manage memory during runtime.

Uploaded by

Vansh Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Course Code: 202000212

Course Title: OBJECT ORIENTED


PROGRAMMING

Chapter:1
Pointers in C, Dynamic Memory Allocation and File
management

-Prof. Arkesha Shah


Pointers
• variable which stores the address of another variable.
Declaring a pointer

• The pointer in c language can be declared using * (asterisk


symbol).
• It is also known as indirection operator.

1.int a*;//pointer to int


2.char *c;//pointer to char
Pointer Example
• By the help of * indirection operator, we can print the
value of pointer variable p.
#include <stdio.h>
int main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %d \n",p);
printf("Value of p variable is %d \n",*p);
printf("Value of p variable is %d \n",&p);
return 0;
}
• * is also called the dereference operator.
int* pc, c; int* pc, c;
c = 5; c = 5;
pc = &c; pc = &c;
c = 1;
*pc = 1;
printf("%d", c);
printf("%d", *pc);
printf("%d", *pc);
printf("%d", c);
Output:?
#include <stdio.h>
int main() { Will below statments give
Error?
int c = 5;
int *p = &c; ⮚ int *p = &c;
printf("%d", *p);
return 0;
} ⮚ int *p:
⮚ p = &c;
NULL Pointer
• If you don't have any address to be specified in the pointer at
the time of declaration, you can assign NULL value.
• Which is known as the NULL pointer.
• int *p=NULL;
#include <stdio.h>
int main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %d",p);
return 0;
}
Output:
The value of pointer is 0
• Pointer to Pointer
• we can also define a pointer to store the address of another
pointer.
• Such pointer is known as a double pointer (pointer to
pointer).
• The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of
the first pointer.
• The syntax of declaring a double pointer is given below.

1.int **p; // pointer to a pointer which is pointing to an int


eger.
Example
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a;
pp = &p;
printf("address of a: %x\n",p);
printf("address of p: %x\n",pp);
printf("value stored at p: %d\n",*p);
printf("value stored at pp: %d\n",**pp);
}
#include<stdio.h>

int main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",*p);
return 0;
}
Program to to swap two number using pointer
#include<stdio.h>
int main( )
{
int a, b, temp ;
int *p1, *p2 ;
printf(" Enter the first number : ") ;
scanf("%d",&a) ;
printf("\n Enter the second number : ") ;
scanf("%d",&b) ;
p1=&a;
p2=&b;
printf("\n Two Number before swapping :%d, %d ",*p1, *p2) ;
temp = *p1 ;
*p1 = *p2 ;
*p2 = temp ;
printf("\n Two Number after swapping :%d, %d ",*p1, *p2) ;
Pointer to Array
#include<stdio.h>

void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
Pointer Arithmetic
• Following arithmetic operations are possible on the pointer:

• Increment
• Decrement
• Addition
• Subtraction
Incrementing Pointer
• If we increment a pointer by 1, the pointer will start pointing
to the immediate next location.

• The Rule to increment the pointer is given below:


• new_address= current_address + i * size_of(data type)

• We can traverse an array by using the increment operation


on a pointer which will keep pointing to every element of
the array
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}
Decrementing Pointer
• If we decrement a pointer, it will start pointing to the
previous location.
• The formula of decrementing the pointer is given below:If
we decrement a pointer,
• it will start pointing to the previous location. The formula of
decrementing the pointer is given below:
• new_address= current_address - i * size_of(data type)
#include <stdio.h>
void main(){
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p);
}
Pointer Addition
• We can add a value to the pointer variable. The formula of
adding value to pointer is given below:
• new_address= current_address + (number * size_of(data ty
pe))
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Pointer Subtraction
• we can subtract a value from the pointer variable.
• Subtracting any number from a pointer will give an address.
• The formula of subtracting value from the pointer variable is
given below:
• new_address= current_address -
(number * size_of(data type))
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Pointer to function
• declaration of the pointer variable must be the same as the function.
#include<stdio.h>
int addition ();
int main ()
{
int result;
int (*ptr)();
ptr = &addition;
result = (*ptr)();
printf("The sum is %d",result);
}
int addition()
{
int a, b;
printf("Enter two numbers?");
scanf("%d %d",&a,&b);
return a+b;
void pointer

• Address assigned to a pointer should be of the same type as specified


in the pointer declaration.
• For example, if we declare the int pointer, then this int pointer cannot
point to the float variable or some other type of variable, i.e., it can
point to only int type variable.
• To overcome this problem, we use a pointer to void.
• A pointer to void means a generic pointer that can point to any data
type.
• We can assign the address of any data type to the void pointer.
Syntax of void pointer

void *pointer name;

Declaration of the void pointer is given below:

void *ptr;
The void pointer in C cannot be dereferenced directly.

#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*ptr);
return 0;
}
#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
return 0;
}
we typecast the void pointer to the integer pointer by using the
statement given below:

(int*)ptr;

Then, we print the value of the variable which is pointed by the void
pointer 'ptr' by using the statement given below:

*(int*)ptr;
Dynamic Memory Allocation

• array is a collection of a fixed number of values.


• Once the size of an array is declared, you cannot change it.
• Sometimes the size of the array you declared may be
insufficient.
• To solve this issue, you can allocate memory manually during
run-time. This is known as dynamic memory allocation in C
programming.
Dynamic memory allocation in c language is possible by 4 functions of
stdlib.h header file.

malloc()
calloc()
realloc()
free()
quick look at the methods used for dynamic memory allocation.
C malloc()

• The name "malloc" stands for memory allocation.


• The malloc() function reserves a block of memory of the specified
number of bytes.
• it returns a pointer of void which can be casted into pointers of any
form.
Syntax of malloc()
ptr = (castType*) malloc(size);
ptr = (float*) malloc(100 * sizeof(float));
• The above statement allocates 400 bytes of memory.
• It's because the size of float is 4 bytes.

• the pointer ptr holds the address of the first byte in the allocated
memory.

• The expression results in a NULL pointer if the memory cannot be


allocated.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
calloc()
• The name "calloc" stands for contiguous allocation.
• The calloc() function allocates multiple block of requested memory.
• The malloc() function allocates memory and leaves the memory
uninitialized,
• whereas the calloc() function allocates memory and initializes all bits to
zero.
• Syntax of calloc()

ptr = (castType*)calloc(n, size);


Example:

ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25


elements of type float.
example of calloc() function.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc()
• If the dynamically allocated memory is insufficient or more than required,
• you can change the size of previously allocated memory using the realloc()
function.

• Syntax of realloc()

ptr = realloc(ptr, x);


Here, ptr is reallocated with a new size x.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Addresses of previously allocated memory:\n");


for(i = 0; i < n1; ++i)
printf("%d\n",ptr + i);

printf("\nEnter the new size: ");


scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%d\n", ptr + i);

free(ptr);

return 0;
}
free()
• Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on their own.

• You must explicitly use free() to release the space.

• Syntax of free()
• free(ptr);

• This statement frees the space allocated in the memory pointed by ptr.
File Handling in C
Why files are needed?
• When a program is terminated, the entire data is lost.
• Storing in a file will preserve your data even if the program
terminates.
• It helps in preserving the data or information for reusability.
• And without loss of data, we can easily transfer the contents of a
file.
File Operations

• File handling in C enables us to create, update, read, and delete the files.
• In C, you can perform four major operations on files,
• Creation of a file
• Opening a file
• Reading a file
• Writing to a file
• Closing a file
Types of Files

• When dealing with files, there are two types of files:


1. Text files
2. Binary files
1) Text files
• Text files are the normal .txt files. You can easily create text files
using any simple text editors such as Notepad.
• When you open those files, you'll see all the contents within the file
as plain text.
• You can easily edit or delete the contents.
• easily readable
2) Binary files

• Binary files are mostly the .bin files in your computer.

• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
• not readable easily
Functions for file handling:
How to Create a File
A file is nothing but space in a memory where data is stored.
Syntax:

FILE *fp;
fp = fopen ("file_name", "mode");
For example,

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");
• fopen is a standard function which is used to open a file.
• If the file is not present on the system, then it is created and then
opened.
• If a file is already present on the system, then it is directly opened
using this function.
• fp is a file pointer which points to the type file.
• Whenever you open or create a file, you have to specify what you
are going to do with the file.
• A file in ‘C’ programming can be created or opened for
reading/writing purposes.
• A mode is used to specify whether you want to open a file for any of
the below-given purposes.
Example

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}
Output:
File is created in the same folder where you have saved your code.
You can specify the path where you want to create your file
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("D://data.txt", "w");
}
How to Close a file
The file (both text and binary) should be closed after reading/writing.

fclose (file_pointer);

Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
Reading and writing to a text file

• For reading and writing to a text file,


• we use the functions fprintf() and fscanf().
include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
Reading File : fscanf() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}
fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}
C fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into file.
Example:
#include <stdio.h>
Void main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
fgetc() function

• The fgetc() function returns a single character from the file.

#include<stdio.h> while((c=fgetc(fp))!=EOF){
void main(){ printf("%c",c);
FILE *fp; }
char c; fclose(fp);
fp=fopen("myfile.txt","r"); getch();
}
C fputs() and fgets()
• The fputs() and fgets() in C programming are used to write and read
string

#include<stdio.h>
void main(){
FILE *fp;
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
fgets()

#include<stdio.h>
void main(){
FILE *fp;
char text[300];

fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}
ftell() function
• The ftell() function returns the current file position of the specified
stream

• Syntax:

• long int ftell(FILE *stream)


fseek() in C
• It is used to move or change the position of the file pointer which is
being used to read the file, to a specified position.

• Syntax of fseek()
• fseek(FILE * stream, long int offset, int whence);
• The first parameter stream is the pointer to the file.
• The second parameter is the position of the record to be found.
• third parameter specifies the location where the offset starts.
It can have the following three values

SEEK_END : denotes the end of the file


SEE_SET : denotes the starting of the file
SEEK_CUR : denotes the current position of the file pointer.
Example:-
#include <stdio.h>

int main()
{
// declaring a file pointer
FILE *filePointer;

// opening the file in read mode


filePointer = fopen("test.txt", "r");

// using ftell(), printing the filePointer's current position


printf("The current location of file pointer is %d pos from the start of
the file\n", ftell(filePointer));
// using fseek(), setting the filePointer's position as 4 offsets
fseek(filePointer, 4, SEEK_SET);

// using ftell(), printing the filePointer's current position


printf("The current location of file pointer is %d pos from the start of the
file\n", ftell(filePointer));

// closing the file


fclose(filePointer);
Output:
return 0; ● The current location of file pointer is 0 pos from the start
} of the file
● The current location of file pointer is 4 pos from the start
of the file
Thank You

You might also like