Module 5 Pointers & Files

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

MODULE 5

What are Pointers in C?

The pointers perform the function of storing the addresses of other variables in the program.
These variables could be of any type- char, int, function, array, or other pointers. The pointer sizes
depend on their architecture. But, keep in mind that the size of a pointer in the 32-bit architecture
is 2 bytes.

Example.

int x = 10;

int* p = &x;

Here, the variable p is of pointer type, and it is pointing towards the address of the x variable,
which is of the integer type.

How Do We Use Pointers in C?

Consider that we are declaring a variable “a” of int type, and it will store a value of zero.

int a = 0

Now, a is equal to zero.

Declaration of a Pointer

Just like the variables, we also have to declare the pointers in C before we use them in any
program. We can name these pointers anything that we like, as long as they abide by the naming
rules of the C language. Normally, the declaration of a pointer would take a form like this:

data_type * name_of_pointer_variable;

Note that here,

 The data_type refers to this pointer’s base type in the variable of C. It indicates which
type of variable is the pointer pointing to in the code.
 The asterisk ( * ) is used to declare a pointer. It is an indirection operator, and it is the
same asterisk that we use in multiplication.

We can declare pointers in the C language with the use of the asterisk symbol ( * ). It is also
called the indirection pointer, as we use it for dereferencing any pointer. Here is how we use it:

int *q; // a pointer q for int data type

char *x; // a pointer x for char data type

The Initialization of a Pointer

Once we declare a pointer, we then initialise it just like the standard variables using an address of
the variable. In case we don’t initialise the pointers in any C program and start using it directly,
the results can be pretty unpredictable and potentially disastrous.

We use the & (ampersand) operator to get the variable’s address in the program. We place the &
just before that variable’s name whose address we require. Here is the syntax that we use for the
initialisation of a pointer,

Syntax of Pointer Initialization

pointer = &variable;

Let us look at an example of how we can use pointers for printing the addresses along with the
value.

#include<stdio.h>

int main(){
int digit=100;

int *r;

r=&digit;

printf(“The address of the variable r is equal to %x \n”,r);

printf(“The value of the variable r is equal to %d \n”,*r);

return 0;

The output

The address of the variable r is equal to fff4

The value of the variable r is equal to 100

OPERATORS

Operator Name Uses and Meaning of


Operator

* Asterisk Declares a pointer in a


program.
Returns the referenced
variable’s value.

& Ampersand Returns a variable’s


address

The Pointer to an Array

Here is an example to illustrate the same,

int arr [20];


int *q [20] = &arr; // The q variable of the pointer type is pointing towards the integer array’s
address or the address of arr.

The Pointer to a Function

Here is an example to illustrate the same,

void display (int);

void(*q)(int) = &show; // The q pointer is pointing towards the function’s address in the program

The Pointer to a Structure

Here is an example to illustrate the same,

struct str {

int x;

float y;

}ref;

struct str *q = &ref;

Types of Pointers

There are various types of pointers that we can use in the C language. Let us take a look at the
most important ones.
The Null Pointer

The null pointer has a value of 0. To create a null pointer in C, we assign the pointer with a null
value during its declaration in the program. This type of method is especially useful when the
pointer has no address assigned to it. Let us take a look at a program that illustrates how we use
the null pointer:

#include <stdio.h>

int main()

int *a = NULL; // the null pointer declaration

printf(“Value of the variable a in the program is equal to :\n%x”,a);

return 0;

The output obtained out of the program mentioned above will be:

Value of the variable a in the program is equal to: 0

The Void Pointer

The void pointer is also known as the generic pointer in the C language. This pointer has no
standard data type, and we create it with the use of the keyword void. The void pointer is
generally used for the storage of any variable’s address. Let us take a look at a program that
illustrates how we use the void pointer in a C program:

#include <stdio.h>

int main()

void *q = NULL; // the void pointer of the program

printf(“Size of the void pointer in the program is equal to : %d\n”,sizeof(q));

return 0;
}

The output obtained out of the program mentioned above will be:

Size of the void pointer in the program is equal to : 4

The Wild Pointer

We can call a pointer a wild pointer if we haven’t initialized it with anything. Such wild pointers
are not very efficient in a program, as they may ultimately point towards some memory location
that is unknown to us. It will ultimately lead to some problems in the program, and then, it will
crash. Thus, you must be very careful when using wild pointers in a program. Let us take a look
at a program that illustrates how we use the wild pointer in a C program:

#include <stdio.h>

int main()

int *w; // the wild pointer in the program

printf(“\n%d”,*w);

return 0;

The output obtained out of the program mentioned above will be a compile-time error.

Here are a few more types of pointers that you can find in the C programs:

 Near pointer

 Complex pointer

 Huge pointer

 Far pointer

 Dangling pointer
Accessing Pointers- Indirectly and Directly

There are basically two ways in which a program can access a variable content and then
manipulate it:

 Direct Access: In this case, we use the variable name in the program directly.

 Indirect Access: In this case, we use some pointers to the variables in the program.

Let us take a look at a program to understand this better. Consider the below program:

#include <stdio.h>

/* Declaration and initialization of an int variable in the program */

int variable = 1;

/* Declaration of the pointer to the int variable */

int *ptr;

int main( void )

/* Initialization of ptr to the point to the variable */

ptr = &variable;

/* Accessing var indirectly and directly */

printf(“\nThe direct access of the variable would be = %d”, variable);

printf(“\nThe indirect access of the variable would be = %d”, *ptr);

printf(“\n\nOutput of the address of the variable would be = %d”, &variable);

printf(“\nOutput of the address of the variable would be = %d\n”, ptr);

*ptr=48;

printf(“\nThe indirect access of the variable would be = %d”, *ptr);

return 0;

The compilation of this program devoid of errors would generate an output like this:
The direct access of the variable would be = 1

The indirect access of the variable would be = 1

Output of the address of the variable would be = 4202496

Output of the address of the variable would be = 4202496

The indirect access of the variable would be = 48

Pros of using Pointers in C

 Pointers make it easy for us to access locations of memory.

 They provide an efficient way in which we can access the elements present in the
structure of an array.

 We can use pointers for dynamic allocation and deallocation of memory.

 These are also used to create complex data structures, like the linked list, tree, graph, etc.

 It reduces the code and thus improves the overall performance. We can use it to retrieve
the strings, trees, and many more. We can also use it with structures, arrays, and
functions.

 We can use the pointers for returning various values from any given function.

 One can easily access any location of memory in the computer using the pointers.

Cons of Pointers in C

 The concept of pointers is a bit tricky to understand.

 These can lead to some errors like segmentation faults, accessing of unrequired memory
locations, and many more.

 A pointer may cause corruption of memory if we provide it with an incorrect value.

 Pointers in a program can lead to leakage of memory.

 As compared to all the other variables, pointers are somewhat slower.

 Some programmers might find it very tricky to deal with pointers in a program. It is their
responsibility to use these pointers and manipulate them carefully.
The & Address of Operator in C

This operator basically returns the variable’s address. But keep in mind that we must use the %u
if we want to display the variable’s address.

#include<stdio.h>

int main(){

int digit=100;

printf(“The value of the digit is equal to %d and the address of the digit is equal to
%u”,digit,&digit);

return 0;

The output of the program mentioned above would be like this:

The value of the digit is equal to 100 and the address of the digit is equal to fff4

File Handling in C

In programming, we may require some specific input data to be generated several


numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.

o Creation of the new file

o Opening an existing file


o Reading from the file

o Writing to the file

o Deleting the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is
used to open a file. The syntax of the fopen() is given below.

FILE *fopen(const char *file_name, const char *mode_of_operation);

Parameters: The method accepts two parameters of character type:  


1. file_name: This is of C string type and accepts the name of the file
that is needed to be opened.
2. mode_of_operation: This is also of C string type and refers to the
mode of the file access.
z

Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing
all the operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );  

EXAMPLE

1. #include<stdio.h>  
2. void main( )  

3. {  
4. FILE *fp ;  
5. char ch ;  
6. fp = fopen("file_handle.c","r") ;  
7. fclose (fp ) ;  

8. }  

Output

The content of the file will be printed.

C fseek() function

The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)  

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.

Example:

1. #include <stdio.h>  
2. void main(){  
3.    FILE *fp;  
4.   
5.    fp = fopen("myfile.txt","w+");  
6.    fputs("This is javatpoint", fp);  
7.     
8.    fseek( fp, 7, SEEK_SET );  
9.    fputs("sonoo jaiswal", fp);  
10.    fclose(fp);  
11. }  

myfile.txt

This is sonoo jaiswal

C rewind() function

The rewind() function sets the file pointer at the beginning of the stream. It is useful
if you have to use stream many times.

Syntax:

1. void rewind(FILE *stream)  

Example:

File: file.txt

1. this is a simple text  

File: rewind.c

1. #include<stdio.h>  
2. #include<conio.h>  
3. void main(){  
4. FILE *fp;  
5. char c;  
6. clrscr();  
7. fp=fopen("file.txt","r");  
8.   
9. while((c=fgetc(fp))!=EOF){  
10. printf("%c",c);  
11. }  
12.   
13. rewind(fp);//moves the file pointer at beginning of the file  
14.   
15. while((c=fgetc(fp))!=EOF){  
16. printf("%c",c);  
17. }  
18.   
19. fclose(fp);    
20. getch();    
21. }    

Output:

this is a simple textthis is a simple text

C ftell() function

The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end of
file. We can use SEEK_END constant to move the file pointer at the end of file.

Syntax:

1. long int ftell(FILE *stream)  

Example:

File: ftell.c

Play Video

1. #include <stdio.h>  
2. #include <conio.h>  
3. void main (){  
4.    FILE *fp;  
5.    int length;  
6.    clrscr();  
7.    fp = fopen("file.txt", "r");  
8.    fseek(fp, 0, SEEK_END);  
9.   
10.    length = ftell(fp);  
11.   
12.    fclose(fp);  
13.    printf("Size of file: %d bytes", length);  
14.    getch();  
15. }  

Output:

Size of file: 21 bytes

fread() function reads the entire record at a time.


Syntax
fread( & structure variable, size of (structure variable), no of records, file pointer);

Example

struct emp{

   int eno;

   char ename [30];

   float sal;

} e;

FILE *fp;

fread (&e, sizeof (e), 1, fp);


The fwrite() function writes an entire record at a time.
Syntax
fwrite( & structure variable , size of structure variable, no of records, file

pointer);

Example

struct emp{

   int eno:

   char ename [30];

   float sal;

} e;

FILE *fp;

fwrite (&e, sizeof(e), 1, fp);

feof()
The function feof() is used to check the end of file after EOF. It tests the end of file indicator.
It returns non-zero value if successful otherwise, zero.

Here is the syntax of feof() in C language,

int feof(FILE *stream)

Example
#include <stdio.h>

int main() {

   FILE *f = fopen("new.txt", "r");

   int c = getc(f);

   while (c != EOF) {

      putchar(c);

      c = getc(f);
   }

   if (feof(f))

   printf("\n Reached to the end of file.");

   else

   printf("\n Failure.");

   fclose(f);

   getchar();

   return 0;

Output
This is demo!

This is demo!

Reached to the end of file.

Lookup table
In computer science, a lookup table (LUT) is an array that replaces runtime computation
with a simpler array indexing operation. The process is termed as "direct addressing" and
LUTs differ from hash tables in a way that, to retrieve a value  with key , a hash table would
store the value  in the slot  where  is a hash function i.e.  is used to compute the slot, while in
the case of LUT, the value  is stored in slot , thus directly addressable.

typedef in C
The typedef is a keyword used in C programming to provide some meaningful
names to the already existing variable in the C program

. It
behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of
an already existing variable.
Syntax of typedef
1. typedef <existing_name> <alias_name>  
2. #include <stdio.h>  
3. int main()  
4. {  
5. typedef unsigned int unit;  
6. unit i,j;  
7. i=10;  
8. j=20;  
9. printf("Value of i is :%d",i);  
10. printf("\nValue of j is :%d",j);  
11. return 0;  
12. }  

Error Handling in C programs


lthough C does not provide direct support to error handling (or exception
handling), there are ways through which error handling can be done in C. A
programmer has to prevent errors at the first place and test return values
from the functions.
A lot of C function calls return a -1 or NULL in case of an error, so quick test
on these return values are easily done with for instance an ‘if statement’. For
example, In Socket Programming , the returned value of the functions like
socket(), listen() etc. are checked to see if there is an error or not. Different
methods of Error handling in C
1. Global Variable errno: When a function is called in C, a variable
named as errno is automatically assigned a code (value) which can
be used to identify the type of error that has been encountered. Its
a global variable indicating the error occurred during any function
call and defined in the header file errno.h.
Different codes (values) for errno mean different types of errors.
Below is a list of few different errno values and its corresponding
meaning:
2.perror() and strerror(): The errno value got above indicate the types of
error encountered.
If it is required to show the error description, then there are two functions that
can be used to display a text message that is associated with errorno. The
functions are:
 perror: It displays the string you pass to it, followed by a colon, a
space, and then the textual representation of the current errno
value.
strerror(): returns a pointer to the textual representation of the
current errno value
3.Exit Status: The C standard specifies two constants: EXIT_SUCCESS
and EXIT_FAILURE, that may be passed to exit() to indicate successful or
unsuccessful termination, respectively. These are macros defined in stdlib.h.

4.Divide by Zero Errors: A common pitfall made by C programmers is not


checking if a divisor is zero before a division command. Division by zero
leads to undefined behavior, there is no C language construct that can do
anything about it. Your best bet is to not divide by zero in the first place, by
checking the denominator.

You might also like