PROGRAMMING in C UNIT-3 notes
PROGRAMMING in C UNIT-3 notes
CSE, MAIT
Pointers
• As you know, every variable is a memory
location and every memory location has its
address defined which can be accessed using
ampersand & operator, which denotes an
address in memory.
• A pointer is a variable whose value is the
address of another variable, i.e., direct
address of the memory location. Like any
variable or constant, you must declare a
pointer before you can use it to store any
variable address.
CSE, MAIT
Print the address of the variables defined:
#include<stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
Output
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
CSE, MAIT
Declaration of a Pointer
type *var-name;
• Here, type is the pointer's base type; it must
be a valid C data type and var-name is the
name of the pointer variable. The asterisk *
you used to declare a pointer is the same
asterisk that you use for multiplication.
CSE, MAIT
Some more declaration format of pointers
• int *ip; /* pointer to an integer */
• double *dp; /* pointer to a double */
• float *fp; /* pointer to a float */
• char *ch /* pointer to a character */
• ** pointer to a pointer.
CSE, MAIT
How to use Pointers
• There are few important operations, which we
will do with the help of pointers very
frequently.
1. We define a pointer variable
2. Assign the address of a variable to a pointer
3. Finally access the value at the address
available in the pointer variable.
This is done by using unary operator * that
returns the value of the variable located at
the address specified by its operand.
CSE, MAIT
#include<stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer
variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
CSE, MAIT
Output
• Address of var variable: bffd8b3c
//hexadecimal.a-f, 0-9= ffffffffffffffff
• Address stored in ip variable: bffd8b3c
• Value of *ip variable: 20 = Var
CSE, MAIT
NULL Pointers in C
• A pointer that is assigned NULL is called a null
pointer.
• The NULL pointer is a constant with a value of
zero defined in several standard libraries.
#include<stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
Output
The value of ptr is 0.
CSE, MAIT
Advantages of Pointers
1) Pointer reduces the code and improves the
performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures,
and functions.
2) We can return multiple values from a
function using the pointer.
3) It makes you able to access any memory
location in the computer's memory.
CSE, MAIT
Address Of (&) Operator
The address of operator '&' returns the address of a
variable. But, we need to use %u to display the
address of a variable.
#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of
number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4.
CSE, MAIT
Pointer to Array
• int arr[10];
• int *p[10]=&arr; // Variable p of type pointer
is pointing to the address of an integer array
arr.
CSE, MAIT
Pointer to a Function
• void show (int);
• void(*p)(int) = &display; // Pointer p is
pointing to the address of a function
CSE, MAIT
Reading complex pointers
• (): This operator is a bracket operator used to
declare and define the function.
• []: This operator is an array subscript operator
• * : This operator is a pointer operator.
• Identifier: It is the name of the pointer. The
priority will always be assigned to this.
• Data type: Data type is the type of the variable
to which the pointer is intended to point. It
also includes the modifier like signed int, long,
etc)
CSE, MAIT
How to read the pointer:
• int (*p)[10].
• To read the pointer, we must see that () and [] have the
equal precedence. Therefore, their associativity must
be considered here. The associativity is left to right, so
the priority goes to ().
• Inside the bracket (), pointer operator * and pointer
name (identifier) p have the same precedence.
Therefore, their associativity must be considered here
which is right to left, so the priority goes to p, and the
second priority goes to *.
• Assign the 3rd priority to [] since the data type has the
last precedence.
• eg. int (*p)(int (*)[2], int (*)void))
CSE, MAIT
• int (*p)(int (*)[2], int (*)void))
• This pointer will be read as p is a pointer to
such function which accepts the first
parameter as the pointer to a one-
dimensional array of integers of size two and
the second parameter as the pointer to a
function which parameter is void and return
type is the integer.
CSE, MAIT
Double Pointer (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.
• int **p; // pointer to a pointer which is pointin
g to an integer.
CSE, MAIT
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of
pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stored at the address
contained by p i.e. 10 will be printed
printf("value stored at pp: %d\n",**pp); // value stored at the
address contained by the pointer stored at pp
}
pp= 10 (abc) p= 10(xyz);(abc) a(xyz) =10
CSE, MAIT
• Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
CSE, MAIT
Relationship between arrays and pointers
Arrays and pointers are closely related in C. In fact an array
declared as
int A[10]; 0,1,2,3,4,5,6,7,8,9 A[4];
can be accessed using its pointer representation.
The name of the array A is a constant pointer to the first
element of the array. So A can be considered a const int*.
Since A is a constant pointer, A = NULL would be an illegal
statement. Arrays and pointers are synonymous in terms of
how they use to access memory. But, the important
difference between them is that, a pointer variable can take
different addresses as value whereas, in case of array it is
fixed.
CSE, MAIT
CSE, MAIT
Argument passing using pointers
#include <stdio.h>
#include <time.h>
void getSeconds(unsigned long *par);
int main () {
unsigned long sec;
getSeconds( &sec ); /* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}
CSE, MAIT
Array of Pointers
Simple program of 3 variables
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, var[i] );
} return 0;
}
Var[0] =10, Var[1] = 100, Var[2]= 200,
CSE, MAIT
Output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
CSE, MAIT
Same Program using Pointers
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */ }
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
} return 0;
}
CSE, MAIT
Find the area and the perimeter of a circle using call by reference function.
#include<stdio.h>
Void areaperi( int, float*, float*);
Void main() {
Int radius;
Float area, perimeter;
Printf(“Enter radius of a circle”);
Scanf(“%d”,&radius);
Areaperi(radius, &area, &perimeter);
Printf(“Area= %f”, area);
Printf(“\nPerimeter = %f”, perimeter);}
Void areaperi(int r, float *a, float *p)
{ *a= 3.14*r*r;
*p = 2 * 3.14 *r}
CSE, MAIT
Pointers to functions
• In C, like normal data pointers (int *, char *, etc), we can have pointers to functions.
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}
• Output:
• Value of a is 10
CSE, MAIT
How to declare a pointer to a function?
1) Unlike normal pointers, a function pointer points to code, not
data. Typically a function pointer stores the start of
executable code.
• 2) Unlike normal pointers, we do not allocate de-allocate
memory using function pointers.
•
3) A function’s name can also be used to get functions’
address.
{
void (*fun_ptr)(int) = fun; // & removed
fun_ptr(10); // * removed
return 0;
}
4) Like normal pointers, we can have an array of function
pointers.
CSE, MAIT
5) Function pointer can be used in place of switch case. For example, in below program, user is
asked for a choice between 0 and 2 to do different tasks.
#include <stdio.h>
void add(int a, int b)
{ printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{ printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{ printf("Multiplication is %d\n", a*b);
}
int main()
{ // fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;
printf("Enter Choice: 0 for add, 1 for subtract and 2 ""for multiply\n");
scanf("%d", &ch);
if (ch > 2) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
Output:- Enter Choice: 0 for add, 1 for subtract and 2 for multiply 2 Multiplication is 150
CSE, MAIT
6) Like normal data pointers, a function pointer can be passed as an
argument and can also be returned from a function.
#include <stdio.h>
void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }
// A function that receives a simple function as parameter and calls
the function
void wrapper(void (*fun)())
{
fun();
}
int main()
{
wrapper(fun1);
wrapper(fun2);
return 0;
} CSE, MAIT
Strings and Pointer
• a string is a sequence of characters which we save in an
array. And in C programming language the \0 null character
marks the end of a string.
• Creating a string
• In the following example we are creating a
string str using char character array of size 6.
• char str[6] = "Hello";
• The above string can be represented in memory as follows.
CSE, MAIT
Creating a pointer for the string
• The variable name of the string str holds the address of the first element of the
array i.e., it points at the starting memory address.
• So, we can create a character pointer ptr and store the address of the
string str variable in it. This way, ptr will point at the string str.
• In the following code we are assigning the address of the string str to the
pointer ptr.
• char *ptr = str;
• We can represent the character pointer variable ptr as follows.
• The pointer variable ptr is allocated memory address 8000 and it holds the address
of the string variable str i.e., 1000.
CSE, MAIT
Accessing string via pointer
• To access and print the elements of the string we can use a loop and check
for the \0 null character.
• In the following example we are using while loop to print the characters of
the string variable str.
#include <stdio.h>
int main(void) {
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0') {
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++;
}
return 0;
}
CSE, MAIT
Using Pointer to Store String
• We can achieve the same result by creating a character
pointer that points at a string value stored at some
memory location.
CSE, MAIT
Structure
• Structure stores the different types of
elements i.e heterogeneous elements.
The struct keyword is used to define structure.
Syntax
struct structure_name
{
data_type member1;
data_type memeberN;
};
CSE, MAIT
Simple Program Using Structure
#include <stdio.h>
#include <string.h>
struct student {
int rollno;
char name[60];
}s1; //declaring s1 variable for structure
void main( ) {
//store first employee information
s1.rollno=1;
strcpy(s1.name, “Aman”);//copying string into char array
//printing first employee information
printf( "Rollno : %d\n", s1.rollno);
printf( "Name : %s\n", s1.name);
}
CSE, MAIT
Output
Rollno : 1
Name : Aman
CSE, MAIT
Additional Features of Structure
• The values of a structure variable can be
assigned to another structure variable of the
same type using the assignment operator.
• One structure can be nested within another
structure. Using this facility, complex data
types can be created.
• Like an ordinary variable, a structure variable
can also be passed to a function.
• The way we can have a pointer pointing to an
int, or a pointer pointing to a char, similarly we
can have a pointer pointing to a struct.
CSE, MAIT
Uses of Structure
• Changing the size of the cursor
• Changing the content of the screen
• Placing the cursor at an appropriate position
on screen.
• Receiving a key from keyboard.
• Displaying the directory of a disk
• Sending the output to printer
• Interacting with the mouse.
• Hiding the file from the directory.
CSE, MAIT
Union
• Union also stores the different types of elements
i.e heterogeneous elements. The union keyword
is used to define structure. Union takes the
memory of largest member only so occupies less
memory than structures.
Syntax
union union_name {
data_type member1;
data_type memeberN;
}Variable1, Variable2..;
CSE, MAIT
Simple Program Using Union
#include <stdio.h>
#include <string.h>
union student {
int rollno;
char name[60];
}s1;
//declaring s1 variable for union
void main( ) {
//store first employee information
s1.rollno=1;
strcpy(s1.name, “Aman”);//copying string into char array
//printing first employee information
printf( "Rollno : %d\n", s1.rollno);
printf( "Name : %s\n", s1.name);
}
CSE, MAIT
Output
Output
Rollno : 3546656
Name : Aman
Rollno takes garbage value because name has
large memory size. So only name will have
actual value.
CSE, MAIT
Difference between Structure and Union
• Structure and union both are user defined data types
which contains variables of different data types. Both of
them have same syntax for definition, declaration of
variables and for accessing members. Still there are many
difference between structure and union. In this tutorial
we will take a look on those differences.
• In structure each member get separate space in memory.
Take below example.
• struct student { int rollno; char gender; float marks; }s1;
• The total memory required to store a structure variable is
equal to the sum of size of all the members. In above
case 7 bytes (2+1+4) will be required to store structure
variable s1.
CSE, MAIT
• In union, the total memory space allocated is equal to the member with
largest size. All other members share the same memory space. This is the
biggest difference between structure and union.
• union student { int rollno; char gender; float marks; }s1;
• In above example variable marks is of float type and have largest size (4
bytes). So the total memory required to store union variable s1 is 4 bytes.
• We can access any member in any sequence.
• s1.rollno = 20; s1.marks = 90.0; printf("%d",s1.rollno);
• The above code will work fine but will show erroneous output in the case
of union. We can access only that variable whose value is recently stored.
• s1.rollno = 20; s1.marks = 90.0; printf("%d",s1.rollno);
• The above code will show erroneous output. The value of rollno is lost as
most recently we have stored value in marks. This is because all the
members share same memory space.
• All the members can be initialized while declaring the variable of
structure. Only first member can be initialized while declaring the variable
of union. In above example we can initialize only variable rollno at the
time of declaration of variable.
CSE, MAIT
BASIS OF COMPARISON STRUCTURE UNION
Basic The separate memory location is All members of the 'union' share
allotted to each member of the the same memory location.
'structure'.
Way of Viewing Provide single way to view each Provide multiple way to to view
memory location. same memory location.
CSE, MAIT
A simple program
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
OUTPUT
Greeting message: Hello
CSE, MAIT
String Functions and their purpose
S No. Function Purpose
CSE, MAIT
String library functions
• strcat ( )Concatenates str2 at the end of str1
• strncat ( )Appends a portion of string to another Hello Wolrd
• strcpy ( )Copies str2 into str1
• strncpy ( )Copies given number of characters of one string to
another
• strlen ( )Gives the length of str1
• strcmp ( )Returns 0 if str1 is same as str2. Returns <0 if strl <
str2. Returns >0 if str1 > str2
• strcmpi ( )Same as strcmp() function. But, this function negotiates
case. “A” and “a” are treated as same.
• strchr ( )Returns pointer to first occurrence of char in str1
• strrchr ( )last occurrence of given character in a string is found
• strstr ( )Returns pointer to first occurrence of str2 in str1
• strrstr ( )Returns pointer to last occurrence of str2 in str1
CSE, MAIT
• strdup ( )Duplicates the string
• strlwr ( )Converts string to lowercase
• strupr ( )Converts string to uppercase
• strrev ( )Reverses the given string.- gnirts
• strset ( )Sets all character in a string to given
character
• strnset ( )It sets the portion of characters in a
string to given character
• strtok ( )Tokenizing given string using delimiter
CSE, MAIT
Basic File Operations in C
Programming
• There are 4 basic operations that can be
performed on any files in C programming
language. They are,
• Opening/Creating a file
• Closing a file
• Reading a file
• Writing in a file
CSE, MAIT
1. fopen() – To open a file.
• Declaration: FILE *fopen (const char *filename,
const char *mode)
• fopen() function is used to open a file to perform
operations such as reading, writing etc. In a C
program, we declare a file pointer and use
fopen() as below. fopen() function creates a new
file if the mentioned file name does not exist.
• FILE *fp;
fp=fopen (“filename”, ”‘mode”);
• Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of
the file.
CSE, MAIT
2. fclose() – To close a file.
• Declaration: int fclose(FILE *fp);
• fclose() function closes the file that is being
pointed by file pointer fp. In a C program, we
close a file as below.
fclose (fp);
CSE, MAIT
3. fgets() – To read a file.
• Declaration: char *fgets(char *string, int n,
FILE *fp)
• fgets function is used to read a file line by
line. In a C program, we use fgets function as
below.
fgets (buffer, size, fp);
• where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer
CSE, MAIT
4. fprintf() – To write into a file.
Declaration:
int fprintf(FILE *fp, const char *format,
…);fprintf() function writes string into a file
pointed by fp. In a C program, we write string
into a file as below.
fprintf (fp, “some data”); or
fprintf (fp, “text %d”, variable_name);
CSE, MAIT
Simple program for writing in file
# include <stdio.h> keyboard” \
# include <string.h> “ to write in the file test.c" ) ;
// getting input from user
int main( ) while ( strlen ( gets( data ) ) > 0 )
{ {
FILE *fp ; // writing in the file
char data[50]; fputs(data, fp) ;
// opening an existing file fputs("\n", fp) ;
printf( "Opening the file test.c in }
write mode" ) ; // closing the file
fp = fopen("test.c", "w") ; printf("Closing the file test.c") ;
if ( fp == NULL ) fclose(fp) ;
{ return 0;
printf( "Could not open file test.c" }
);
return 1;
}
printf( "\n Enter some text from
CSE, MAIT
OUTPUT
• Opening the file test.c in write mode
• Enter some text from keyboard to write in the
file test.c
Hai, How are you?
Closing the file test.c
CSE, MAIT
Simple program to read from a file
# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf( "Opening the file test.c in read mode" ) ;
fp = fopen( "test.c", "r" ) ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "Reading the file test.c" ) ;
while( fgets ( data, 50, fp ) != NULL )
printf( "%s" , data ) ;
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
CSE, MAIT
Output
• Opening the file test.c in read mode
• Reading the file test.c
• Hai, How are you?
• Closing the file test.c
CSE, MAIT
Modes and Description of file
1. r
Opens an existing text file for reading purpose.
2. w
Opens a text file for writing. If it does not exist, then a new file is created.
Here your program will start writing content from the beginning of the file.
3. a
Opens a text file for writing in appending mode. If it does not exist, then a
new file is created. Here your program will start appending content in the
existing file content.
4. r+
Opens a text file for both reading and writing.
5. w+
Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.
6. a+
Opens a text file for both reading and writing. It creates the file if it does not
exist. The reading will start from the beginning but writing can only be
appended.
CSE, MAIT
Basic functions for file
• fopen()create a new file or open a existing file
• fclose()closes a file
• getc()reads a character from a file
• putc()writes a character to a file
• fscanf()reads a set of data from a file
• fprintf()writes a set of data to a file
• getw()reads a integer from a file
• putw()writes a integer to a file
• fseek()set the position to desire point
• ftell()gives current position in the file
• rewind()set the position to the begining point
CSE, MAIT
Difference between Sequential and Random Access
Files
• When we are talking about sequential or random
access to data files we refer to the way data is written
or read from a file on a computer system.
• Sequential Access to a data file means that the
computer system reads or writes information to the file
sequentially, starting from the beginning of the file and
proceeding step by step.
• On the other hand, Random Access to a file means
that the computer system can read or write
information anywhere in the data file. This type of
operation is also called “Direct Access” because the
computer system knows where the data is stored
(using Indexing) and hence goes “directly” and reads
the data.
CSE, MAIT
• Sequential access has advantages when you
access information in the same order all the
time. Also is faster than random access.
• On the other hand, random access file has the
advantage that you can search through it and
find the data you need more easily (using
indexing for example). Random Access
Memory (RAM) in computers works like that.
• As a quick example, modern computer hard
disks are using Random Access whereas Tape
Storage devices (used for offline backups) use
Sequential Access.
CSE, MAIT
File Positioning
• The file position of a stream describes where
in the file the stream is currently reading or
writing. I/O on the stream advances the file
position through the file.
• During I/O to an ordinary disk file, you can
change the file position whenever you wish,
so as to read or write any portion of the file.
Some other kinds of files may also permit this.
Files which support changing the file position
are sometimes referred to as random-
access files.
CSE, MAIT
• The C library function int fseek(FILE *stream, long int
offset, int whence) sets the file position of the stream to
the given offset.
• Declaration
int fseek(FILE *stream, long int offset, int whence)
Parameters
• stream − This is the pointer to a FILE object that identifies
the stream.
• offset − This is the number of bytes to offset from whence.
• whence − This is the position from where offset is added. It
is specified by one of the following constants −
1SEEK_SET- Beginning of file
2SEEK_CUR- Current position of the file pointer
3SEEK_END- End of file
Return Value- This function returns zero if successful, or else
it returns a non-zero value.
CSE, MAIT
Sample Example
#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is ITP Class", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
CSE, MAIT
Output
• This is C Programming Language
CSE, MAIT