PPS Unit - IV
PPS Unit - IV
UNIT - IV
Pointers - Introduction, Pointers for Inter-Function Communication, Pointers to Pointers, Compatibility,
L -value and R-value, Arrays and Pointers, Pointer Arithmetic and Arrays, Passing an Array to a
Function, Memory Allocation Functions, Array of Pointers, Programming Applications, Pointers to
void, Pointers to Functions, Command-line Arguments.
Strings - Concepts, C Strings, String Input / Output Functions, Arrays of Strings, String Manipulation
Functions
------------------------------------------------------------------------------------------------------------------------------
Introduction
A pointer is a constant or a variable that contains the address of another variable.
Computers use their memory for storing the instructions of a program and values of the variables that
are associated with it. The computer‟s memory is a sequential collection of “storage cells”, commonly
known as a byte, has a number called address associated with it. Typically, the addresses are numbered
consecutively, starting from 0. The last address depends on the memory size. A computer system having
64k memory will have its last address as 65,535
1
Subject: PPS Unit – III
Whenever a variable is declared, the system allocates an appropriate location to hold the value of the
variable. Since every byte has a unique address, this location will have its own address.
Example: int x=200;
This instructs the system to find a location for the integer variable x and puts the value 200 in it. Assume
the system has chosen the address location 4000 for x. it is represented as below.
X Name of variable
200 Value of variable
Since memory addresses are simply numbers, they can be assigned to some variables which can be
stored in memory, like any other variable. Such variables that hold memory addresses are called
pointers.
A Pointer is a variable that contains an address which is a location of another variable in memory.
Since pointer is a variable, its value is also stored in the memory in another memory location.
Suppose the address of „quantity‟ is assigned to a variable „p‟. The link between the variables „p‟ and
„quantity‟ can be visualized as shown below
Example: int quantity = 179
P=& quantity
179
Quantity 500
500
P 5050
Since the value of „p‟ is the address of „quantity‟, we may access the value of quantity by using the
value of „p‟. Therefore, the variable „p‟ points to the variable „quantity‟. Thus „p‟ gets the name pointer.
Operators used in pointer:
There are two basic operators used with pointers
1. The address operator: &(ampersand, address of )
2. The indirection operator: *(asterisk, dereferencing, indirection operator)
2
Subject: PPS Unit – III
An address operator gives the address of a variable, while the indirection operator gives the value of the
variable that the pointer is pointing to.
Accessing the Address of a Variable
The actual location of a variable in the memory is system dependent. Therefore, the address of a variable
is not known to us immediately. The address of a variable can be determined with the help of the address
(&) operator available in „C‟. The use of this address (&) operator we have already discussed in the
“scanf()” function. The address (&) operator immediately preceding a variable returns the address
of the variable associated with it.
Example: p=&quantity;
Would assign the address 500 (the location of „quantity‟) to the variable „p‟. The address (&) operator
can be called as „address of‟. The address (&) operator can be used only with a simple variable or an
array element.
If „x‟ is an array, then expressions such as &x[0]
&x[i+3]
are valid and represent addresses of 0th and (i+3)th elements of x.
Features of Pointers:
Pointers save memory space.
Execution time with pointers is faster because data are manipulated with the address, that is, direct
access to memory location.
Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as
well. Hence it can be said the Memory of pointers is dynamically allocated.
Pointers are used with data structures. They are useful for representing two-dimensional and multi-
dimensional arrays.
An array, of any type, can be accessed with the help of pointers, without considering its subscript
range.
Pointers are used for file handling.
Pointers are used to allocate memory dynamically.
Pointer Definition:
Pointer is the derived data type of C. The pointer is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other pointer.
3
Subject: PPS Unit – III
Declaration of Pointers:
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.
The syntax to declaration a pointer variable is:
data_type *name_of_pointer_variable;
Note: This tells the compiler three things about the variable name_of_pointer_variable
1. The asterisk (*) tells that the variable name_of_pointer_variable is a pointer variable
2. name_of_pointer_variable needs a memory location
3. name_of_pointer_variable points to a variable of type data_type .
Example: int *p;
The above declaration tells that the variable „p‟ as a pointer variable that points to an integer data-
type. The type „int‟ refers to the data-type of the variable being pointed to by „p‟ and not the type of
the value of the pointer.
Example: float *x;
The above declaration tells that the variable „x‟ as a pointer to a floating point variable.
Initialization of Pointer
Once we declare a pointer, we then initialize it just like the standard (fundamental type) variables using
an address of the variable. In case we don‟t initialize the pointers in the program and start using it
directly, the results can be unpredictable and potentially disastrous.
We use the address „&‟ (ampersand) operator to get the variable‟s address in the program. We place the
address „&‟ (ampersand) operator just before that variable‟s name whose address we require.
The syntax to initialize a pointer is:
pointer-variable-name = &variable-name;
Example: p=&quantity;
Which causes „p‟ to point to „quantity‟ i.e. „p‟ now contains the address of „quantity‟. This is known as
pointer initialization.
Note: Before a pointer is initialized, it should not be used.
Pointer variables always point to the corresponding type of data.
Example: int a,b;
int *p;
p=&a;
b=*p;
4
Subject: PPS Unit – III
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the sense that
instead of pointing to the data, they point to the code.
Consider a function prototype – int func (int, char), the function pointer for this function will be
Syntax: int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer. Such pointers
are called double-pointers or pointers-to-pointer. Instead of pointing to a data value, they point to
another pointer.
Syntax: data-type ** pointer_name;
Dereferencing Double Pointer
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note: In C, we can create multi-level pointers with any number of levels as shown below
***ptr3, ****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be created by
assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.
Syntax: data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any associated data
type. They are also called generic pointers as they can point to any type and can be type casted to any
type.
Syntax: void * pointer_name;
Note: One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of C-
pointers can cause problems in our programs and can eventually cause them to crash. If values are
updated using wild pointers, they could cause data abort or data corruption.
7
Subject: PPS Unit – III
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be modified
once it is defined. It will always point to the same memory address.
Syntax: data_type * const pointer_name;
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here
we can only access the data pointed by the pointer, but cannot modify it.
Syntax: const data_type * pointer_name;
Pointers for Inter-Function Communication
One of the most useful applications of pointers is in functions. When we discussed functions in
the unit – 2, we saw that C uses the pass-by-value for upward, bi-directional communication, the only
direct way to send something back to the calling function from a called function is through the return
statement.
We also saw that we can use upward and bi-directional communication by passing an address
and using it to refer back to data in the calling program. When we pass an address, we are actually
passing a pointer to a variable. Hence when we need to send more than one value back from a
function, we use pointers. We use either upward or bi-directional communication to send any number
of variables to the calling function.
/* Program which returns multiple values to calling function pointer using pointer variable */
#include <stdio.h>
void compare(int a, int b, int* add_great, int* add_small)
{
if (a > b)
{
// a is stored in the address pointed
// by the pointer variable *add_great
*add_great = a;
*add_small = b;
8
Subject: PPS Unit – III
else
{
*add_great = b;
*add_small = a;
}
}
int main()
{
int biggest, smallest, x, y;
printf("Enter two numbers: \n");
scanf("%d%d", &x, &y);
// The last two arguments are passed
// by giving addresses of memory locations
compare(x, y, &biggest, &smallest);
printf("\nThe greater number is %d and the smaller number is %d", biggest, smallest);
}
Output:
Enter two Numbers: 30 20
The greater number is 30 and the smaller number is 20
Pointers to Pointers (Double Pointer)
A variable in C that stores the address of another variable is known as a pointer. A pointer can store the
address of another pointer too, in which case it is called "pointer to pointer" (also called "double
pointer"). A "pointer to a pointer" is a form of multiple indirections or a chain of pointers.
Declaration of Pointer to a Pointer
The declaration of a pointer to pointer (double pointer) is similar to the declaration of a pointer, the only
difference is that we need to use an additional asterisk (*) before the pointer variable name.
The syntax to declare a double pointer is:
data-type **pointer-variable-name;
Example: int **p;
float **p1; char **p2;
9
Subject: PPS Unit – III
Output:
Value of 'a' is: 100
Value of 'a' using pointer (ptr) is: 100
Value of 'a' using double pointer (dptr) is: 100
Compatibility:
It is important to recognize that pointers have a type associated with them. They are not just pointer
types, but rather are pointers to a specific type. Each pointer therefore takes on the attributes of the type
to which it refers in addition to its own attributes.
Pointer Size Compatibility
The size of all pointers is the same. Every pointer variable holds the address of one memory location in
the computer. On the other hand, the size of the variable that the pointer references can be different; it
takes the attributes of the type of the variable it is being referenced.
10
Subject: PPS Unit – III
12
Subject: PPS Unit – III
Lvalue:
In C, an expression is either an Lvalue or an Rvalue. As we know, every expression has a value. But the
value in an expression (after evaluation) can be used in two different ways.
1. An Lvalue expression must be used whenever the object is receiving a value; that is, it is being
modified.
2. An Rvalue expression can be used to supply a value for further use; that is, to examine or copy its
value.
L-value refers to memory location which identifies an object. L-value may appear as either left hand or
right hand side of an assignment operator (=). L-value often represents as identifier. Expressions
referring to modifiable locations are called “modifiable L-values“. L-value can be called as “locator
value”, and referred to expressions that locate (designate) objects.
The L-value is one of the following:
The name of the variable of any type
i.e. an identifier of integral, floating, pointer, structure, or union type.
A subscript ([ ]) expression that does not evaluate to an array.
A unary indirection (*) expression that does not refer to an array.
An L-value expression in parentheses.
A const object (a non-modifiable L-value).
The result of indirection through a pointer provided that it isn‟t a function pointer.
The result of member access through pointer (-> or .)
Example piece of code for L-values
// declare „a‟ as int variable and „p‟ as pointer variable
int a, *p;
p = &a; // ok, assignment of address at l-value
&a = p; // error: &a is an r-value
13
Subject: PPS Unit – III
int x, y;
( x < y ? y : x) = 0; // It‟s valid because the ternary
// expression preserves the "lvalue-ness"
// of both its possible return values
Rvalue:
R-value” refers to data value that is stored at some address in memory. A R-value is an expression, that
can‟t have a value assigned to it, which means R-value can appear on right but not on left hand side of
an assignment operator(=).
R-value simply means, an object that has no identifiable location in memory (i.e. having an address).
Anything that is capable of returning a constant expression or value. Expression like a+b will return
some constant. All expressions that are not Lvalue expressions are Rvalues.
Base Address
The name „x‟ is defined as a constant pointer to the first element, x[0] and therefore the values of x
is 1000, the location where x[0] is stored, i.e.
x=&x[0]=1000;
If „p‟ is an integer pointer, then the pointer „p‟ points to the array „x‟ by the following assignment:
p=x; is same as p=&x[0];
14
Subject: PPS Unit – III
every value of an array „x‟ can be accessed using p++ to move from one element to another. The
relationship between „p‟ and „x‟ is shown below:
p=&x[0] (=1000)
p+1=&x[1] (=1002)
p+2=&x[2] (=1003)
p+3=&x[3] (=1006)
Note: Address of an element is calculated using its index and the scale factor of the data type.
Example: address of x[3]=base address+(3 * scale factor of int)
=1000 + (3*2) =1006
/*Example program using pointer and Array for 1D array*/
#include<stdio.h>
int main()
{
int i;
int a[5]={1,2,3,4,5};
int *p=&a[0];
for(i=0;i<5;i++)
{
printf(%d\n”,*p);
p++;
}
}
// Example program using pointer and Array for 2D array *
#include<stdio.h>
int main()
{
int a[3][2]={100,200,300,400,500,600},i,j,*ptr;
ptr=&a[0][0];
for(i=0;i<3;i++)
for(j=0;j<2;j++)
{
printf("Element = %d\n",*ptr);
ptr++;
15
Subject: PPS Unit – III
}
}
Pointer Arithmetic
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The
pointer variables store the memory address of another variable. It doesn‟t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for mathematical
calculations.
The following are the Arithmetic operations that can be performed on pointers.
1. Add an integer value to a pointer.
Example: if “p” is a pointer then p++, p+2 is valid
2. Subtract an integer value from a pointer
Example: if “p” is a pointer then p--, p-2 is valid
3. Compare two pointers if they point to the elements of the same array.
Example: if “p” is a pointer then p>p+2 is valid
4. Subtract one pointer from another pointer if both points to the same array.
Example: if “p”, “p1” are pointers then p - p1 is valid
5. Assign one pointer to another pointer provided both are of the same type.
Example: if “p”, “p1” are pointers then p = p1 is valid
The following are the Arithmetic operations that cannot be performed on pointers:
1. Addition of two pointers
Example: if “p”, “p1” are pointers then p + p1 is invalid operation
2. Subtraction of a pointer from another pointer when they do not point to the same array.
Example: if “p”, “p1” are pointers then p - p1 is invalid operation
3. Multiplication of two pointers
Example: if “p”, “p1” are pointers then p *p1 is invalid operation
5. Division of one pointer by another pointer.
Example: if “p”, “p1” are pointers then p / p1 is invalid operation
Passing an Array to Function
In C, there are various general problems which require passing more than one variable of the same type
to a function. For example, consider a function which sorts the 10 elements in ascending order. Such a
function requires 10 numbers to be passed as the actual parameters from the main function. Here, instead
16
Subject: PPS Unit – III
of declaring 10 different numbers and then passing into the function, we can declare and initialize an
array and pass that into the function. This will resolve all the complexity since the function will now
work for any number of values.
As we know that the array_name contains the address of the first element. Here, we must notice that we
need to pass only the name of the array in the function which is intended to accept an array. The array
defined as the formal parameter will automatically refer to the array specified by the array name defined
as an actual parameter.
The syntax of function prototype/ declaration which receives entire 1D array as argument is:
return-type function-name (data-type array-name[], data-type array-size);
The syntax of function call which receives entire 1D array as argument is:
function-name(array-name, arry-size);
The syntax of function definition which receives entire 1D array as argument is:
return-type function-name(array-name[], array-size)
{
local variable declarations;
statement 1;
statement 2;
--------
--------
return statement; //if any return value
}
The syntax of function prototype/ declaration which receives entire 2D array as argument is:
return-type function-name (data-type array-name[][col-size], data-type row-size , data-type col-size);
The syntax of function call which receives entire 2D array as argument is:
function-name(array-name, row-size, col-size );
The syntax of function definition which receives entire 2D array as argument is:
return-type function-name(data-type array-name[][col-size], data-type row-size , data-type col-size)
{
local variable declarations;
statement 1;
statement 2;
--------
--------
17
Subject: PPS Unit – III
scanf("%d",&A[i][j]);
doStuff(A,r,c);
}
void doStuff(int x[][10],int row,int col)
{
int i,j;
printf("The array elements are\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d\t", x[i][j]);
printf("\n");
}
}
Memory Allocation Functions
The process of reserving memory is called allocation. In C memory can be allocated in two different
ways,
Static Memory Allocation
Dynamic Memory Allocation
Static Memory
Static Memory is memory that is reserved for variables before the program runs. Allocation of static
memory is also known as Compile Time Memory Allocation. C automatically allocates memory for
every variable when the program is compiled.
Static memory allocation requires that the declaration and definition of memory should be
specified in the source program.
19
Subject: PPS Unit – III
If memory is allocated at compile time, it cannot be changed during execution. There will be a
problem of either insufficiency or else wastage of memory.
The solution is to create memory dynamically i.e. as per the requirement of the user during
execution of the program.
Dynamic Memory
Dynamic Memory is memory that is allocated after the program starts running. Allocation of dynamic
memory can also be referred to as Runtime Memory Allocation.
It uses predefined functions to allocate and release memory for the data while the program is running.
It postpones the data definition, but not data declaration. Unlike static memory allocation, dynamic
memory allocation does not have an identifier, it has only an address that must be used to access it, and
therefore we must use pointers.
“C” Dynamic Memory Allocation
It can be defined as a procedure in which the size of a data structure (like Array) is changed during the
runtime.
Why do we use Dynamic Memory Allocation?
Since C is a structured language, it has some fixed rules for programming. One of them includes
changing the size of an array. An array is a collection of items stored at contiguous memory locations
As it can be seen that the length (size) of the array above is 9. But what if there is a requirement to
change this length (size). For Example,
If there is a situation where only 5 elements are needed to be entered in this array. In this case,
the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen
the length (size) of the array from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there
is a need to enter 3 more elements in this array. In this case, 3 more indices are required. So, the
length (size) of the array needs to be changed from 9 to 12.
20
Subject: PPS Unit – III
The above two situations cannot be handle by using Static Memory Allocation. Hence to handle such a
situation we use Dynamic Memory Allocation.
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate Dynamic
Memory Allocation in C programming. They are:
1.malloc()
2.calloc()
3.free()
4.realloc()
1) malloc ( ):
This function is used for allocating a block of memory in bytes at runtime.
It returns a void pointer, which points to the base address of allocated memory
The allocated memory is not initialized, so it will contain garbage values.
The malloc() function allocates a block of memory of requested size and returns a pointer to the
first byte of the block.
Syntax:
void *malloc (size in bytes);
The type-casting format of malloc function is:
Pointer-varible=(type *) malloc(size) to make portability, the size is computed by using sizeof operator.
Example:
1) int *ptr; ptr = (int * ) malloc (1000);
2) int *ptr; ptr = (int * ) malloc (n * sizeof (int));
Note: if the memory is not free, it returns NULL
21
Subject: PPS Unit – III
22
Subject: PPS Unit – III
Syntax:
new_pointer = (datatype*) realloc (old_pointer, newsize);
23
Subject: PPS Unit – III
24
Subject: PPS Unit – III
25
Subject: PPS Unit – III
Array of Pointers
A pointer array is a homogeneous collection of indexed pointer variables that are references to a
memory location. It is generally used in Programming when we want to point at multiple memory
locations of a similar data type in our program. We can access the data by dereferencing the pointer
pointing to it.
Syntax:
pointer_type *array_name [array_size];
Here,
pointer_type: Type of data the pointer is pointing to.
array_name: Name of the array of pointers.
array_size: Size of the array of pointers.
Note: It is important to keep in mind the operator precedence and associativity in the array of pointers
declarations of different type as a single change will mean the whole different thing.
For example, enclosing *array_name in the parenthesis will mean that array_name is a pointer to an
array.
// program to demonstrate the use of array of pointers
#include <stdio.h>
int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
int i;
// array of pointers to integers
int *ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for ( i = 0; i < 3; i++)
{
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
}
26
Subject: PPS Unit – III
27
Subject: PPS Unit – III
Pointers to Functions
A pointer is a variable that stores the address of another variable. Like a variable, a function has a type
(data type) and address location in memory. So it is possible to declare a pointer variable to a function.
The syntax to declare a pointer to function is:
type (*fptr) ();
This tells the compiler that “fptr” is a pointer to function, which returns type value. The parenthesis
around “*fptr” is necessary.
Note: if we declare type *gprt() will be considered as function returning pointer type.
We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
For example
int mul(int, int);
int (*p) ();
p=mul;
Now “mul” can be called using the below statement
(*p) (x,y); //function call
// program1 to demonstrate pointer to functions
#include <stdio.h>
// Defining a function
void hello()
{
printf("Hello World");
}
int main()
{
// Declaring a function pointer
28
Subject: PPS Unit – III
29
Subject: PPS Unit – III
STRINGS
Strings Concept
String is a data type that represents a sequence of characters, such as letters, numbers, symbols, and
spaces. Strings are often used in programming to store and manipulate text. (OR)
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. Each character in the
array occupies one byte of memory, and the last character must always be '\0'. 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.
Some of the important things about the strings are:
Enclosed in quotation marks: Strings are enclosed in double quotations.
For example, "liquid" and "What is liquid? It's a template language" are both strings.
Case sensitive: Strings are case sensitive.
Implemented as an array: Strings are often implemented as an array data structure of bytes or words.
Different in different programming languages: How strings are treated can vary between
programming languages. For example, in Java, strings are objects of the String class, while in other
languages they are treated as arrays of characters.
String Declaration Syntax:
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to define the
length of the string, i.e. the number of characters strings will store.
There is an extra terminating character which is the Null character („\0‟) used to indicate the termination
of a string that differs from normal arrays.
30
Subject: PPS Unit – III
String Initialization:
We can initialize string in 4 different ways which are as follows:
Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the
compiler, a null character „\0‟ is appended at the end of the string by default.
31
Subject: PPS Unit – III
There are mainly two types of these functions available in the C language:
Formatted
The formatted functions basically present or accept the available data (input) in a specific format. The
standard library in C contains various functions for the input-output operations. The scanf() and printf()
out of these functions help a programmer format the functions in their desired format. The program can
use these functions for reading any form of data, like a real number, an integer, a character, and many
more.
Unformatted
The unformatted functions are not capable of controlling the format that is involved in writing and
reading the available data. Thus, these functions constitute the most basic forms of output and input. The
supply of input or the display of output isn‟t allowed in the user format – thus, we call these functions
unformatted functions for input and output.
The unformatted input-output functions further have two categories:
The character functions
The string functions
We use the character input functions for reading only a single character from the input device (the
keyboard). On the other hand, we use the character output functions for writing just a single character on
the output source (the screen). Here, the getchar(), getche(), and the getch() refer to the input functions
of unformatted type, while the putchar() and putch() refer to the output functions of unformatted type.
The string output and input. In any programming language, the character array or string refers to the
collection of various characters. Now, various types of input and output functions are present in C
programming that can easily read and write these strings. The puts() and gets() are the most commonly
used ones. Here, the gets() refers to the input function used for reading the string characters while the
puts() refers to the output function used for writing the string characters (in unformatted forms).
// C program to read and print a character using getcha() and putchar()
#include <stdio.h>
int main()
{
int character;
printf("Enter any random character between a-z: ");
character = getchar();
32
Subject: PPS Unit – III
Arrays of Strings
Definition:
An array of strings is a two-dimensional array of character-type arrays where each character array
(string) is null-terminated.
Declaration of an Array of Strings
To declare an array of strings, we need to declare a two-dimensional array of character types, where the
first subscript is the total number of strings and the second subscript is the maximum size of each string.
Syntax of array of string declaration is:
char strings [no_of_strings] [max_size_of_each_string];
Here:
no_of_strings: specifies maximum number of strings that can be stored.
max_size_of_each_string: specifies maximum number of characters each string contains.
34
Subject: PPS Unit – III
Example:
char *langs[10];
char *langs[no. of strings]={“list of strings separated by commas”};
char *langs[10] = {
"PYTHON", "JAVASCRIPT", "PHP",
"NODE JS", "HTML", "KOTLIN", "C++",
"REACT JS", "RUST", "VBSCRIPT"
}; // initialization of an array of strings with pointers
35
Subject: PPS Unit – III
b) char str[10]=”INDIA”
int len;
len=strlen(str);
36
Subject: PPS Unit – III
not, it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters. The prototype of this function is
int strcmp(const char *s1,const char *s2);
char city1[20]=”CULCUTTA”;
strcpy(city,”DELHI”);
By the above statement the string constant “DELHI” will be copied in a string called “city”.
strcpy(city2,city1);
By the above statement the string “city1” will be copied in a string called “city2”.
NOTE: The size of the target string should be greater or equal to the size of the source string.
char lname[20]=”John”;
char fname[20]=”Hello”;
strcat(fname, lname);
37
Subject: PPS Unit – III
On concatenating will result into target string (i.e. fname) “HelloJohn”. That is source string is added at
the end of target string. So target string containing the combined string.
C allows the nesting of “strcat()” function
Example: strcat(strcat(str1,str2),str3);
Is allowed and concatenates all the three strings together. The result is stored in “str1”.
NOTE: The size of the target string should be large enough to join the source string.
Example: strrev(str);
#include <stdio.h>
#include<string.h>
int main ( )
{
char s1 [100], s2 [100], a [100], b [100];
int n;
printf ("Enter the first string: ");
gets (s1);
printf ("Enter the second string: ");
gets (s2);
n=strlen(s1);
printf("\nLenght of first string is: %d\n",n);
n=strlen(s2);
printf("Lenght of second string is: %d\n",n);
if(strcmp (s1, s2)==0)
printf("\nStrings are equal\n");
else
printf("\nStrings are not equal\n");
38
Subject: PPS Unit – III
39