0 ratings0% found this document useful (0 votes) 43 views36 pagesPointers & 4th Module Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Pointers
C Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-bit
architecture the size of a pointer is 2 byte.
3233 | fa
> number
(pointer) (normal variable)
Advantage of pointer
1) Pointer reduces the code and improves the performance; it is used to retrieving
strings, trees, ete. and used with arrays, structures, and functions.
2) Pointers can be used to return multiple values from a function via function
arguments.
3) Pointers allow C to support dynamic memory management.
4) The use of pointer arrays to character strings results in saving of data storage
space in memory.
5) They increase the execution speed and thus reduce the program execution time.
Declaring a pointer
The declaration of a pointer variable takes the following form:data_type *pt_name;
This tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type
Eg: int *p; //integer pointer
Float *x; // float pointer
Initialization of pointer variables
The process of assigning the address of a variable to a pointer variable is known as
initialization. We generally use the ( & ) addressof operator to get the memory
address of a variable and then store it in the pointer variable.
Eg:-
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same
time.
Eg:-
int *ptr = &var;
Acct a variable throu ter ( Pointer Dereferencin:
Dereferencing a pointer is the process of accessing the value stored in the
memory address specified in the pointer. We use the same ( * ) dereferencing
operator that we used in the pointer declaration.#include
int main()
int num = 100 ,n;
int “ptr; //pointer variable
ptr= num; — //pointer initialization
/ipritning the value
n=*ptr;,
printf("value of num = %d\n", n):
return 0;
Output
value of num = 100
Pointer Arithmetic in C
Pointer Arithmetic is the set of valid arithmetic operations that can be performed
on pointers. These operations are:
1
2
3.
4,
. Increment/Decrement of a Pointer
. Addition of integer to a pointer
Subtraction of integer to a pointer
. Subtracting two pointers of the same type
1, Increment/Decrement of a Pointer
Increment: When a pointer is incremented, it actually increments by the
number equal to the size of the data type for which it is a pointer. For 32-bit
int variable, it will be incremented by 2 bytes. For 64-bit int variable, it will
be incremented by 4 bytes.If an integer pointer that stores address 1000 is incremented, then it will
increment by 4(size of an int), and the new address will point to 1004.
While if a float type pointer is incremented then it will increment by 4(size
of a float) and the new address will be 1004.
Decrement: When a pointer is decremented, it actually decrements by the
number equal to the size of the data type for which it is a pointer
in case of 64 bit os
Eg:
If an integer pointer that stores address 1000 is decremented, then it will
decrement by 4(size of an int), and the new address will point to 996. While if a
float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.
Pointer Increment & Decrement
Memory
996 997 998 999 1000 1001 1002 1003 1004
pire
~4 Bytes +4 Bytes
Eg: for pointer increment
#include
int mainQ)
{int number=S0;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf(" Address of p variable is %u \n",p);
p=p+l;
printf("After increment: Address of p variable is %u \n".p); return 0;
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Eg:- for pointer decrement
#include
void main()
{
int number=50;
int *p;
p=&number;
printf" Address of p variable is %u \n",p);
p=p-l.
printf("After decrement: Address of p variable is %u \n",p);
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
2. Addition of Integer to PointerWhen a pointer is added with an integer value, the value is first multiplied by
the size of the data type and then added to the pointer.
For Example:
Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address. If we add integer 5 to it using the expression, ptr = ptr
+5, then, the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 =
1020.
Pointer Addition
Memory
1000 1004 1008 1012 1016 1020 1024 1028
Eg:-
#include
int mainQ)
{
int number=50;
int *
p=&number;
printf("Address of p variable is %u \n",p);
p=p+3;
printf(""After adding 3: Address of p variable is %u \n",p);
return 0;
i
Output
Address of p variable is 3214864300After adding 3: Address of p variable is 3214864312
3. Subtraction of Integer to Pointer
When a pointer is subtracted with an integer value, the value is first multiplied by
the size of the data type and then subtracted from the pointer
For Example:
Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address. If we subtract integer 5 from it using the
expression, ptr = ptr — 5, then, the final address stored in the ptr will be ptr =
1000 — sizeof(int) * 5 = 980.
EHG
EG
Pointer Subtraction
Memory
72 976 980 984 968 992 996 1000
Eg:
#include
int main’)
(
int number=S0;
int *
p=&number;
printf(" Address of p variable is %u \n",p);P=P-
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300.
After subtracting 3: Address of p variable is 3214864288
4. Subtraction of Two Pointers
‘The subtraction of two pointers is possible only when they have the same data
type. The result is generated by calculating the difference between the addresses
of the two pointers and calculating how many bits of data it is according to the
pointer data type. The subtraction of two pointers gives the increments between
the two pointers.
For Example:
Two integer pointers say ptr (address:1000) and ptr2(address:1004) are
subtracted. The difference between addresses is 4 bytes. Since the size of int is 4
bytes, therefore the increment between ptr and ptr? is given by (4/4) = 1.
#include
int main)
int
int
int *ptrl, *ptr2;
ptrl = &N;
ptr = &x;
printf(" ptrl = %u, ptr2 = %u\n", ptrl, ptr2);
X= ptrl - ptr2;printf("Subtraction of ptrl "& ptr2 is %d\n", x);
return 0;
}
Output
ptrl = 2715594428, ptr2 = 2715594424
Subtraction of ptrl & ptr2 is 1Array of Pointers
‘When we want to point at multiple variables or memories of the same data type
in a C program, we use an array of pointers.
Declaration of an Array of Pointers in C
An array of pointers can be declared just like we declare the arrays of char, float, int,
etc. The syntax for declaring an array of pointers would be:
datatype *arrayname [array_size];
eg:- int *a[55];
Program
#include
int main()
{
int *arr[3];
int p = 40, q = 60, r= 90, i;
arr[0] = &p;
ar[1] = &q;
art[2] = &r;
for(i = 0; i < 3; i++)
if
printf(“For the Address = %d\t the Value would be = %d\n”, arr[i], *arr[i]);
}
return 0;
}
The output generated out of the program mentioned above would be like this:For the Address = 387130656 the Value would be = 40
For the Address = 387130660 the Value would be = 60
For the Address = 387130664 the Value would be = 90
iP q r
ve { Go) (Go) (a)
Address ait 2000 2010 2050
arr[0] arr[1] arr[2]
The arr[i] provides the address of the array’s ith element. Thus, the arr[0] would
return the address of the variable p, the arr[1] would return the address of the pointer
q, and so on. We use the * indirection operator to get the value present at the
address. Thus, it would be like this:
*arr[i]
Thus, *arr[0] would generate the value at the arr[0] address. In a similar manner, the
*arr[1] would generate the value at the arr[1] address, and so on.
Double Pointer (Pointer to Pointer)
A pointer is used to store the address of a variable in C. Pointer reducesthe access time of a variable. However, In C, we can also define a
pointer to store the address of another pointer. Suchpointer 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.
address > address + value
pointer pointer variable
The syntax of declaring a double pointer is
given below. int **p; // pointer to a pointer
which is pointing to an integer. Example:
#include
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);
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10Pointer _to Array
Pointer to an array is also known as array pointer. We are using
the pointer to access the components of the array.
int a[3] = (3, 4, 5 };
int *ptr = a;
We have a pointer ptr that focuses to the Oth component of the array.
Likewise we can declare a pointer that can point to whole array rather
than just a single component of the array.
Syntax:
data type (*var name)[size of array];
Declaration of the pointer to an array:
// pointer to an array of five numbers
int (* ptr)[5] = NULL;
eg:
#include
int main)
{
// Pointer to an array of five numbers
int(*a)[5];
int b[5] = { 1, 2, 3,4, 5 };
inti=0;
a= &b;for (i = 0; i < 5; i++)
{
printf("%d\n", *(*a + i);
}
return 0;
}
Output:
1
2
S
4
5
Array of pointers: “Array of pointers” is an array of the pointer
variables. It is also known as pointer arrays.
Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different
values or we can make one integer array of pointers that can point to all
the values.
Eg:-
#include void main()
{
int arr{] = { 1,2,3 }s
int i, *ptr[3];
for (i = 0; i< 3; i++)
{
ptr[i] = &arr[i);
}
for (i = 0; i< 3; i++)
{
printf(""Value of arr[%d] = %d\n", i, *ptr[i]);
}
}
Output:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3Dynamic Memory Allocation
The process of allocating memory at run time is known as dynamic memory
allocation
Memory Allocation Process
The program instructions and global and static variables are stored in a region known as
permanent storage area and the local variables are stored in another area called stack. The
memory space that is located between these two regions is available for dynamic allocation
during execution of the program. This free memory region is called the heap. The size of the
heap keeps changing when program is executed due to creation and death of variables that are
local to functions and blocks. It is possible to encounter memory “overflow” during dynamic
allocation process. In such situations, the memory allocation functions return a NULL pointer
when they fail to locate enough memory requested.
Allocating a Block of Memory: MALLOC
The malloc() function allocates single block of requested memory.
+ It doesn't initialize memory at execution time, so it has garbage value initially.
- It retums NULL if memory is not sufficient.
‘The syntax of malloc() function is given below
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type. The malloc return a pointer to an area of memory with size
byte-size.
All Multipk ks of mem« ALLThe calloc() function allocates multiple block of requested memory.
- It initially initialize all bytes to zero.
+ Itreturns NULL if memory is not sufficient.
‘The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size);
Altering the size of a block: REALLOC
We can change the memory size already allocated with the help of the function realloc(). This
process is called the reallocation of memory.
Syntax of realloc() function is:-
ptr=realloc(ptr, new-size);
Releasing the used space: FREE
‘The memory occupied by malloc() or calloc() functions must be released by calling free()
function, Otherwise, it will consume memory until program exit
Syntax of free() function is:
free(ptr);String Handling
Strings
The string can be defined as the one-dimensional array of characters terminated by
a null (\0’). The character array or the string is used to manipulate text such as
word or sentences. The termination character (\0') is important in a string since it is
the only way to identify where the string ends. When we define a string as char
s[10], the character s[10] is implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Example of declaring string by char array in C
language. char greeting[6] = {'H’, 'e
0};
While declaring string, size is not mandatory. So we can write the above code as given
below:
char ch[]={'H’, '
0;
We can also define the string by the string literal in C language. For example
char ch{]="hello";
In such case, "\0" will be appended at the end of the string by the compiler.Index ° a 2 3 4 5
VariableThe C compiler automatically places the '\0' at the end of the string
when it initializes the array.
Example program:
#include
int main () {
char greeting[6] ={"H'Je', I, '','o', \0"};
printf("Greeting message: %s\n",greeting );
return 0;
When the above code is compiled and executed, it
produces the following result — Greeting message: Hello
String- Handling Functions
1, streat() Function
‘The streat() function joins two strings together. It takes the following
form:
streat(string1,string 2);
string] and string2 are character arrays.
Eg:
#include
#include
int main()
‘
char ch{10}=('h, 'e’, ", ','0', \0'};
char ch2[10]=f'c’, \0'};streat(ch,ch2);
printf{" Value of first string is: %s" ch);
return 0;
}
Output:
Value of first string is: helloc
2. stremp() Function
The stremp() function compares two strings identified by the
arguments and has a value 0 if they are equal. If they are not, it has the
numeric difference between the first nonmatching characters in the
string. It takes the form:
stremp(stringl string2);
Example
#include
#include
int main()
char str1[20],str2[20];
printf("Enter Ist string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(stremp(strl ,str2)=0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;Output:
Enter Ist string: hello
Enter 2nd string: hello
Strings are equal
Fg
stremp(“their”,”there”); will return a value of -9 which is the numeric
difference between ASCII “i ” and ASCII “r”. That is , “i” minus “r”
ASCII code is -9. If the value is negative, string] is alphabetically
above string2.
3. strepy() Function
It takes the form:
strepy(string1,string2);
It assigns the contents of string? to string1.
Eg:
#include
#include
int main()
t
char ch{20]={'7, a 'v','a’,'t, 'p,'o', i, ‘n't, \0"};
char ch2[20];
strepy(ch2,ch);
printf(""Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint4. strlen() Function
The strlen() function counts and returns the number of characters of the
given string. It doesn't count the null character ‘\0’. It takes the form:
nestrlen(string);
E
#include
#include
int main()
{
char ch{20}
"a, Va, 't, p07, nyt, NO};
printf(’Length of string is: %d",strlen(ch));
return 0;
Output:
Length of string is: 10
Other String Functions
1. strnempQ) FunctionIn C programming, the string comparison function ‘strnemp()' is used to compare two
strings character by character, up to a specified length
Syntax
The strnemp() function can be carried out via the syntax as follows:
1. int strnemp(char *s1 char *s2, int n);
The three parameters are:
©. 's1’and's2' are the pointers to the two strings that the user wants to compare.
©. 'n'defines the number of characters to be compared between the two strings.
2. strnepy() function
The stmepy() function in C is used to copy the specified number of characters
from one string to another string contiguously. The function will not modify the
source string from which the value is copied.
Syntax of strncpy() Function in C
strnepy(s1,s2,n);
This statement copies the first n characters of the source string s2 into the target
string s}
3. strncat() Function
This concatenation function takes three parameters :-
strneat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1eg:-
sl:
s2:
After strncat(s1,s2,4); execution:
sl:
B A L A G U R U \0
3. strstr function
It is a two-parameter function that can be used to locate a substring in a
string. This takes the form:
strstr(s1,s2);
The function strstr() searches the string s1 to see whether the string s2 is
contained in sl. If yes, the function returns the position of the first occurrence of
the sub-string. Otherwise, it returns a NULL pointer.Structure
‘Structure is a user-defined data type that enables us to store the collection of different data types
at different memory locations. Each element of a structure is called a member. The struct keyword
is used to define the structure.
The syntax to define the structure is:
struct structure_name
{
data_type member;
data_type member2;
data_type member N;
i
The example to define a structure for an entity employee is:
struct employee
(int id;
char name{20};
float salary;
k
‘The following image shows the memory allocation of the structure employee that is defined in the
above example1014
intid ‘char Name[10] float salar,
struct Employee sizeof (emp) = 4+ 10+ 4= 18 bytes
int id where;
char Name[20}; sizeof (int) = 4 byte
float salary; sizeof (char) = 1 byte
emp; sizeot (float) = 4 byte
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure.
tag or structure tag
stuctkeyword
struct employee{
intid; members or
charname[50; ——> elds of
float salary; —————> _ structure
JavaTpointcom
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure easily
There are two ways to declare structure variable:
i
2
By struct keyword within mainQ function
By declaring a variable at the time of defining the structure.Ist way:
To declare the structure variable by struct keyword. It should be declared within the main function.
struct employee
(int id;
char name[50];
float salary;
i
Now write given code inside the main() function.
struct employee el, €2;
‘The variables e1 and e2 can be used to access the values stored in the structure.
2nd way:
Another way to declare variable at the time of defining the structure.
struct employee
(int id;
char name[50};
float salary;
Jel.e2;
Accessing members of the structure
There are two ways to access structure members:
1. By.. (member or dot operator)
2. By -> (structure pointer operator)Structure example
#include
#include
struct employee
{ int id;
char name[S0];
Jel; /declaring e1 variable for structure
void main( )
{
store first employee information
elid=101;
strepy(el.name, "Ram")://copying string into char array
printing first employee information
printi( “employee 1 id : 9d\n", e1id);
printi( "employee 1 name : %s\n", e1 name);
getch);
}
Output:
employee 1 id: 101
employee | name : RamUnion
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program.
The format of the union statement is as follows ~
union {
member definition;
member definition;
member definition;
} [one or more union variables};
At the end of the union's definition, before the final semicolon, you can specify one or more union
variables but it is optional. Here is the way you would define a union type named Data having
three members i, f, and str—
union Data {
inti;
float f;
char str{20];
} data;Accessing Union Members
To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access. You would use the keyword union to define
variables of union type. The following example shows how to use unions in a program ~
#include
include
union Data {
intis
float f;
char str{20};
k
void main( ) {
union Data data;
data.i = 10;
printf( “data. : 96d\n", data.i);
data.f = 220.5;
printf( “data.f : %f\n", data.f);
strepy( data.str, "C Programming’
printf( "data.str : %s\n", data.str);
getchQ);
}
‘When the above code is compiled and executed, it produces the following result ~data.i: 10
data.f : 220.500000
data.str : C Programming
Difference between Structure and Union
Struct
Union
The struct keyword is used to define a structure.
The union keyword is used to define union.
When the variables are declared in a structure,
the compiler allocates memory to each variable
member. The size of astructure is equal or
greater to the sum of the sizes of each data
member.
When the variable is declared in the union, the
compiler allocates memory to the largest size variable
member. The size of a union is equal to the size of its
largest data membersize.
Each variable member occupied a unique
memory space.
Variables members share the memory space of the
largestsize variable.
Changing the value of a member will not affect
Changing the value of one member will also affect
other variablesmembers. othervariables members.
Each variable member will be assessed at a time. | Only one variable member will be assessed at a time.
We can initialize multiple variables of | In union, only the first data member can be
a structure at a time.
initialized.
Allvariable members store some value at any point
in theprogram.
Exactly only one data members to store a value at
any particularinstance in the program.
The structure allows initializing
multiplevariable members at once.
Union allows initializing only one variable member
atonce.
Itis used to store different data type values.
It is used for storing one at a time from
different datatype values.
It allows accessing and retrieving any data
member at a time.
It allows accessing and retrieving any one data
memberat a time.File Handling in C
File Handling is the storing of data in a file using a program. In C programming
language, the programsstore results, and other data of the program to a file using file
handling in C.
File handling in C enables us to create, update, read, and delete the files stored on
the local filesystem through our C program.
The following operations can be performed on a file.
Creation of the new file
Opening an existing file
Reading from the file
Writing to the file
Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and
close the file.A list of file functions are given below:
1 fopend opens new or existing file
2 fprintf) write data into the file |
3 fscanf) reads data from the file
la " fputeo writes a character into the file
5 fgetc) reads a character from file
6 felose() closes the file
2 fseek) sets the file pointer to given position || 8 fputw0) | writes an integer to file
| 9 fgetw() | reads an integer from file
| 10 frell) | returns current position
| rewind) | sets the file pointer to the beginning of 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 * filename, const char * mode );
‘The fopen() function accepts two parameters:
‘The file name (string). Ifthe file is stored at some specific location, then we must mention the path
at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
‘The mode in which the file is to be opened. It is a string.
‘We can use one of the following modes in the fopen() function.
r opens a text file in read mode
w “opens a text file in write mode
a opens a text file in append mode
tt | ‘opens a text file in read and write mode
we opens a text file in read and write mode
_ | aicisetemuilbinicctlondieninad
rb opens a binary file in read mode
wb | opens a binary file in write mode
ab | opens a binary file in append mode |The fopen function works in the following way.
© Firstly, It searches the file to be opened.
© Then, it loads the file from the disk and place it into the buffer. The buffer is,
used to provide efficiency for the read operations.
© Itsets up a character pointer which points to the first character of the file.
Consider the following example which opens a file in write mode.
#include
void main( )
{
FILE “fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while (1)
{
ch = fete (fp):
if(ch == EOF)
break ;
printf
)
felose (fp)
}
Closing File: felose()
e",ch) ;
The felose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of felose() function is given below:
int felose( FILE *fp );
Writing File : fprintfQ function
‘The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
int fprint{(FILE *stream, const char *format [, argument, ..1)Example:
#include
main((
FILE *fp;
fp = fopen("fileaxt", "w"),/opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
felose(fp)y/closing file
}
Reading File : fscanf() function
‘The fscanf() function is used to read set of characters from file. It reads a word from the
file and returns EOF at the end of file,
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include
void main(){
FILE *fp;
char buff]255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
print buff);
1
felose(tp);