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

Pointers and Strings

The document discusses pointers, dynamic memory allocation, and strings in C programming. It covers pointers concepts like pointer variables, constants, and values. It explains how to declare and initialize pointer variables and access variables through pointers. It also discusses dynamic memory allocation functions like malloc(), calloc(), realloc(), and free(). Finally, it covers string concepts in C like C strings, string input/output functions, and string manipulation functions.

Uploaded by

Vedavyas V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Pointers and Strings

The document discusses pointers, dynamic memory allocation, and strings in C programming. It covers pointers concepts like pointer variables, constants, and values. It explains how to declare and initialize pointer variables and access variables through pointers. It also discusses dynamic memory allocation functions like malloc(), calloc(), realloc(), and free(). Finally, it covers string concepts in C like C strings, string input/output functions, and string manipulation functions.

Uploaded by

Vedavyas V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CPDS UNIT -III

UNIT III:Pointers, Dynamic memory allocation and Strings

Pointers – Introduction (Basic Concepts), Pointers for inter function communication (call by
value and call by reference), pointers to pointers, compatibility, void pointer, null pointer,
dangling pointer, passing an array to a function, Pointer Applications - Arrays and Pointers,
Pointer Arithmetic , Pointer to functions.

Dynamic Memory allocation –Memory allocation functions -malloc(), calloc(), realloc(), free(),
Allocating memory for arrays of different data types,. C program examples.

Strings – Concepts, C Strings, String Input / Output functions, arrays of strings, string
manipulation functions, C program examples.

MITS Page 1
CPDS UNIT -III

POINTERS

INTRODUCTION

A pointer is a variable that stores a memory address of another variable. Pointers are one of the
derived types in C.

Some of the advantages of pointers are listed below:

 A pointer enables us to access a variable that is defined outside the function.


 Execution time with pointer is faster because data is manipulated with the address i.e.
direct access to memory location.
 Pointers are more efficient in handling the data tables.
 Pointers reduce the length and complexity of a program.
 The use of a pointer array to character strings save data storage space in memory.

POINTER CONCEPTS

The basic data types in C are int, float, char double and void. Pointer is a special data
type which is derived from these basic data types.

There are three concepts associated with the pointers are,

 Pointer Constants
 Pointer Values
 Pointer Variables

POINTER CONSTANTS

 As we know, computers use their memory for storing the instructions of a program, as
well as the values of the variables that are associated with it.
 The computer’s memory is a sequential collection of ‘storage cells’.
 Each cell can hold one byte of information, has a unique number associated with it called
as ‘address’.
 The computer addresses are numbered consecutively, starting from zero. The last address
depends on the memory size.
 Let us assume the size of the memory is 64K then,

The total memory locations = 64K


= 64 * 1K
= 64 * 1024 bytes
= 65536 bytes (locations)

 So, here the last address is 65535(started with 0).


 Physically they are divided into even bank and odd bank.

MITS Page 2
CPDS UNIT -III

 Even bank is set of memory locations with even addresses. Like 0, 2, 4, 6……65534.
 Odd bank is set of memory locations with odd addresses. Like 1, 3, 5 ….65535.

Address Memory Locations Address

0 1

2 3

4 5

.. ..

.. ..

32278 32279
.. ..

65530 65531

65532

65534 65535

even bank odd bank

Figure: 4.1 Memory Organization.

 These memory addresses are called pointer constants.


 We cannot change them, but we can only use them to store data values.
 For example, in the above memory organization, the addresses ranging from 0 to 65535
are known as pointer constants.
 Remember one thing, the address of a memory location is a pointer constant and cannot
be changed .

POINTER VALUE

Whenever we declare a variable, the system allocates , an appropriate location to hold the
value of the variable somewhere in the memory,.

Consider the following declaration,

MITS Page 3
CPDS UNIT -III

int i = 10;

This declaration tells the C compiler to perform the following activities:

 Reserve space ( 2 BYTES) in the memory to hold the integer value.


 Associate the name i with this memory location.
 Store the value 10 at this location.

We can represent i’s location in the memory by the following memory map:

i Variable Name

Variable value
10
65510 Variable address

Pointer Values

 Memory is divided into number of storage cells called memory locations.


 Each memory location is assigned with an address
 These address associated with ae variables by the system are called pointer values.
 For example, the address 65510 which is associated to the variable i is a pointer value.

The & Operator

 The address of the variable cannot be accessed directly. The address can be obtained by
using address operator(&) in C language.
 The address operator can be used with any variable that can be placed on the left side of
an assignment operator.
 The format specifier of address is %u(unsigned integer),the reason is addresses are
always positive values. We can also use %x to know the address of a variable.
 Example, to know the address of variable n, just use &n.

Note: Constants, expressions, and array name cannot be placed on the left side of the assignment
and hence accessing address is invalid for constants, array names and expressions.

The following are illegal use of address Operator.

&125 (Pointing at constant)


int a[10];
&a (pointing to array name)
&(x+y) (pointing at expressions)

POINTER VARIABLE

MITS Page 4
CPDS UNIT -III

 A variable Which holds the address of some other variable is called pointer variable.
 A pointer variable should contain always the address only.

The * Operator

 It is called as ‘Value at address’ operator. It returns the value stored at a particular


address.
 It is also Known as Indirection or Dereferencing Operator

ACCESSING A VARIABLE THROUGH POINTER

For accessing the variables through pointers, the following sequence of operations have to be
performed, to use pointers.

1. Declare an ordinary variable.


2. Declare a pointer variable.
3. Initialize a pointer variable(Provide link between pointer variable and ordinary variable).
4. Access the value of a variable using pointer variable.

Declaring a pointer variable

In C , every variable must be declared before they are used. Since the pointer variables
contain address that belongs to a another variable, they must be declared as pointers before we
use them.

The syntax for declaring a pointer variable :


data type *ptr_name;

This tells the compiler three things about the variable ptr_name.

1. The asterisk(*) tells that the variable ptr_name is a pointer variable.


2. ptr_name needs a memory location.
3. ptr_name points to a variable of type data type.

For example,
int *p;

declares the variable p as a pointer variable that points to an integer data type. Remember that
the type int refers to the data type of the variable being pointed by p.

Initializing Pointers

MITS Page 5
CPDS UNIT -III

 Once a pointer variable has been declared, it can be made to point to a variable using
statement such as

ptr_name = &var;
 Which cause ptr_name to point to var.Now ptr_name contains the address of var. This is
known as pointer initialization.
 Before a pointer is initialized it should not be used.

Access the value of a variable using pointer variable

Once a pointer variable has been assigned the address of a variable, we can access the
value of a variable using the pointer. This is done by using the indirection operator(*).

*ptr_name
Example1

MITS Page 6
CPDS UNIT -III

The above program illustrates how to access the variable using pointers. After finding the
first statement i = 10, the compiler creates a variable i with a value of 10 at a memory location.
Then coming to line 2 and 3 a pointer variable pi is create and initialized with the address of the i
variable. then the compiler automatically provides a link between these two variables as follows.
i pi

10 8342

8342 8338

Note: Pointer variable always points to a address of the another variable .


Following statements are not valid with respect to pointers.

int i = 10, k, *pi = &i;


k = pi; // pointer value cannot be accessed by integer
pi = 65506(constant); // we cannot directly assign a value to a pointer variable

Example2

The following code illustrates how to declare int ,char and float pointers. Here we have
declared three variables of type int, float and char ,also three pointer variables points to int, float
and char. Remember here pf points to the value of type float but its type is unsigned integer
only.

MITS Page 7
CPDS UNIT -III

MITS Page 8
CPDS UNIT -III

Declaration versus Redirection:

 When an asterisk is used for declaration, it is associated with a type.


 Example:

int * pa;
int * pb;

 On the other hand, we also use the asterisk for redirection.


When used for redirection, the asterisk is an operator that redirects the operation from the
pointer variable to a data variable.

 Example:
Sum = *pa + *pb;

Dangling Pointers

A pointer variable should contain a valid address. A pointer variable which does not
contain a valid address is called dangling pointer.
For example, consider the following declaration,

int *pi;
This declaration indicates that pi is a pointer variable and the corresponding memory
location should contain address of an integer variable.
But , the declaration will not initialize the memory location and memory contains garbage
value.
CPDS UNIT -III

Note: We cannot use a pointer variable to the register variable. The reason is that, user does not
know the address of the register variable. So we are not able to use pointer variable on register
variables.

POINTER ARITHMETIC

The following operations can be performed on a pointer:


 Addition of a number to a pointer. Pointer can be incremented to point to the next
locations.

Example:
int i=4 ,pi=&i; //(assume address of i=1000)
float j,*pj=&j;// (assume address of j=2000)
pi = pi + 1; // here pi incremented by (1*data type times)
pi = pi + 9; // pi = 1000 + (9*2)  1018 address
pj = pj + 3; // pj=1018+(3*4)1030 address

 Subtraction of a number from a pointer. Pointer can be decremented to point to the


earlier locations.

Example:
int i=4,*pi=&i; //assume address of i =1000)
char c, *pc=&c; // assume address of c = 2000
double d, *pd=&d; // assume address of d=3000
pi = pi-2; /* pi=1000-(2*2)=996 address */
pc = pc-5; /* pc=2000-(5*1)=1985 address
pd = pd-6; /* pd=3000-(6*8)=2952 address */

 Pointer variables may be subtracted from one another. This is helpful while finding
array boundaries. Be careful while performing subtraction of two pointers.

 Pointer variables can be used in comparisons, but usually only in a comparison to NULL.

 We can also use increment/decrement operators with pointers this is performed same as
adding/subtraction of integer to/from pointer.

The following operations cannot be performed on pointers.

 Addition of two pointers.


 Multiplication of a pointer with a constant, two pointers.
 Division of a pointer with a constant, two pointers.

MITS Page 10
CPDS UNIT -III

POINTER EXPRESSIONS

Like other variables, pointer variables can be used in expressions. For example, if p1 and
p2 are two valid pointers ,then the following statements are valid.

a= *p1 + *p2;
sum = sum + *p1;
z = 10 / *p2;
f = *p1 * i;

Note: be careful while writing pointer expressions .The expression *p++ will result in the
increment of the address of p by data type times and points to the new value. Whereas the
expression (*p) ++ will increments the vale at the address. If you are not properly coded you will
get some unwanted result.

NULL Pointer

 If wish to have a pointer that points to “nowhere”, should make this explicit by assigning
it to NULL.
 If it is too early in the code to assign a value to a pointer, then it is better to assign NULL
(i.e., \0 or 0).

double *pval1 = NULL;


double *pval2 = 0;

 The integer constants 0 and 0L are valid alternatives to NULL, but the symbolic constant
is (arguably) more readable.
 A NULL pointer is defined as a special pointer.
 It can be used along with memory management functions.

POINTERS TO POINTERS

 It is possible to make a pointer to point to another pointer variable. But the pointer must
be of a type that allows it to point to a pointer.
 A variable which contains the address of a pointer variable is known as pointer to pointer.
 Its major application is in referring the elements of the two dimensional array.
 Syntax for declaring pointer to pointer,

data type **ptr_ptr;


 This declaration tells compiler to allocate a memory for the variable ptr_ptr in which
address of a pointer variable which points to value of type data type can be stored.
 Syntax for initialization

ptr_ptr=&ptr_name;

MITS Page 11
CPDS UNIT -III

 This initialization tells the compiler that now ptr_ptr points to the address of a pointer
variable.
 Accessing the element value,

**ptr_ptr;

 It is equalent to *(*(&ptr_name));

Example

The above program illustrates the use of pointers to pointers. Here, using two indirection
operators the data item 16 can be accessed (i.e., *ppi refers to pi and **ppi refers to i).

POINTER COMPATIBILITY

 We should not store the address of a data variable of one type into a pointer variable of
another type.
 During assigning we should see that the type of data variable and type of the pointer
variable should be same or compatible. Other wise it will result in unwanted output.
 The following program segment is wrong,

int i=10;

MITS Page 12
CPDS UNIT -III

float *pf;

pf = &i; // data variable is integer and pointer variable is float

It is possible to use incompatible pointer types while assigning with type casting pointer.

Casting pointers :When assigning a memory address of a variable of one type to a pointer that
points to another type it is best to use the cast operator to indicate the cast is intentional (this will
remove the warning).

Example:

int V = 101;
float *P = (float *) &V; /* Casts int address to float * */

Removes warning, but is still a somewhat unsafe thing to do.

void Pointer

 A pointer to void is a generic type that is not associated with a reference type.
 It is neither the address of a character nor an integer, nor a float nor any other type.
 It is compatible for assignment purposes only with all other pointer types.
 A pointer of any reference type can be assigned to a pointer to void type.
 A pointer to void type can be assigned to a pointer of any reference type.
 Certain library functions return void * results.
 No cast is needed to assign an address to a void * or from a void * to another pointer
type.
 Where as a pointer to void can not be deferenced unless it is cast.
void *
void

Figure : pointer to void

 Example 1:

int V = 101;
float f=98.45;
void *G = &V; /* No warning */
printf (“%d”,*((int*)G)); /* Now it will display 101
G = &f; /* No warning, still not safe */
printf (“%f”,*((float*)G)); /* Now it will display 98.45

MITS Page 13
CPDS UNIT -III

 Example 2:

void main()
{
void *p;
int a=32;
float k=43.65;
clrscr();
p=&a;
printf("The value of a=%d",*(int *)p);
p=&k;
printf("\nThe value of k=%f",*(float *)p);
getch();
}

OUTPUT

The value of a=32


The value of k=43.650002

Pointers and arrays


The name of the array represents the base address of the array(address of 0th element)
Ex: int a[5];

MITS Page 14
CPDS UNIT -III

5000 5002 5004 5006 5008

The array name a represents the base address of the array (i.e. 5000)

Example program:
#include<stdio.h>
int main()
{
int a[5] = { 1, 2, 3, 4, 5 };
int *p;
p = a;
printf("The base address of array:%u\n", a);
printf("The address stored in the pointer:%u\n", p);
return 0;
}

OUTPUT

The base address of array:5000


The address stored in the pointer:5000
In this program, we have a pointer p that points to the 0th element of the array.

Pointer to arrays
The pointer that points to whole array instead of only one element of the array is called
pointer to array.

Syntax:

data_type (*var_name)[size_of_array];
Example:

int (*p)[5];

Here p is pointer that can point to an array of 5 integers.Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer name
inside parentheses. Here the type of p is ‘pointer to an array of 5 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different. The following program shows this:

MITS Page 15
CPDS UNIT -III

// C program to understand difference between


// pointer to an integer and pointer to an array of integers.
#include<stdio.h>
int main()
{
int *p1; // Pointer to an integer
int (*p2)[5]; // Pointer to an array of 5 integers
int a[5];
p1 = a; // Points to 0th element of the a
p2 = &a;// Points to the whole array a.
printf("p1 = %p, p2 = %p\n", p1, p2);
p1++;
p2++;
printf("p1 = %p, p2 = %p\n", p1, p2);
return 0;
}

output

p1 = 5000, p2 = 5000
p1 = 5002, p2 = 5010

p1: is pointer to 0th element of the array a, while p2 is a pointer that points to the whole array a.
 The base type of p1 is int while base type of p2 is ‘an array of 5 integers’.
 We know that the pointer arithmetic is performed relative to the base size, so if we write
p2++, then the pointer p2 will be shifted forward by 10 bytes.

MITS Page 16
CPDS UNIT -III

Dynamic Memory Allocation


MEMORY ALLOCATION FUNCTIONS
In C, reserving memory locations for an object can be done in two ways :
1)static allocation
2)Dynamic allocation.
Memory Usage
Conceptually memory is divided into program memory and data memory. Program
memory consists of the memory used for main and functions. Data memory consists of
permanent definitions, such as global data and constants, local declarations and dynamic data
memory. Exactly how C handles these different needs is a function of operating system and the
compiler writer’s skills.
Although the program code for a function may be in memory at all times, the local
variables for function are available only when it is active. Furthermore, more than one version of
the function can be active at a time. In this case, multiple copies of the local variables are
allocated, although only one copy of the function is present. The memory facility for these
capabilities is known as stack memory.
In addition to stack, a memory allocation known as heap is available. Heap memory is
unused memory allocated to the program and available to be assigned during its execution. It is
the memory pool from which memory is allocated when requested by the memory allocation
functions.
Main Function

Program Memory

Global Heap Stack

Data Memory

Conceptual View of Memory

MITS Page 17
CPDS UNIT -III

Memory allocation process

Storage of C program

 The program instructions and global and static variables are stored in the region known
as permanent storage area.
 Local variables are stored in stack area.
 The heap area is used for dynamic memory allocation ata run time.
 The size of the heap keep changing when program is executed due to the creation and
death of variables.
Static Memory Allocation

Static memory allocation requires that the declaration and definition of memory be fully
specified in the source program. The number of bytes reserved cannot be changed during run
time. This is the technique we have used to this point to define variables, arrays, pointers, and
streams.

MITS Page 18
CPDS UNIT -III

Dynamic Memory Allocation

Dynamic memory allocation uses predefined functions to allocate and release memory
for data while the program is running. It effectively postpones the data definition, but not the
data declaration, to run time.

Memory Allocation Functions

Four memory management functions are used with dynamic memory.

They are
malloc()
calloc()
realloc()
free()
First three are used for memory allocation and fourth is used for return memory when it is no
longer needed. All the memory management functions are found in the standard library file
stdlib.h.

Block of Memory Allocation (malloc())

The malloc() function allocates a block of memory that contains the number of bytes
specified in its parameters. It returns a void pointer to the first byte of the allocated memory.
The allocated memory is not initialized.

Function prototype is

void* malloc(size_t size);

The type, size_t is defined in several header files including stdio.h. The type is usually an
unsigned integer.

To provide portability, the size specification in malloc() ’s actual parameter is generally


computed using the sizeof operator. For example, if we want to allocate an integer in the heap,
then we call as follows

MITS Page 19
CPDS UNIT -III

p = malloc(sizeof(int));

malloc function returns the address of the first byte in the memory space allocated. If it
is not successful, it return NULL pointer. An attempt to allocate memory from the heap when the
memory is insufficient is known as overflow. It is up to the program to check for memory
overflow. If it doesn’t the program produces the invalid results or aborts with an invalid address
the first time the pointer is used.

If we call malloc() with a zero size, the results are unpredictable. It may return NULL
pointer or it may return some other implementation dependent value.

Note : Never call malloc with a zero size

Prior to C99, it was necessary to cast the pointer returned from a memory allocation
function. The casting format is

p = (type*) malloc(size);

Ex: p = (int*)malloc(4*sizeof(int));

The compiler allocates the space equal to 4 times of integer.and the address of first byte
is allocated to pInt.

5000

address of first byte

5000

8 bytes of space

MITS Page 20
CPDS UNIT -III

PROGRAM:

#include<alloc.h>

int main()

int *p,*q,x,n,i,j=0;

printf("Enter the value of n:");

scanf("%d",&n);

p=(int *)malloc(n*sizeof(int));

q = p;

printf("Enter values:");

for(i=0;i<n;i++)

scanf("%d",&x);

*p = x;

p++;

printf("\n given values:");

for(i=0;i<n;i++)

printf("%4d",*q);

q++;

return 0;

MITS Page 21
CPDS UNIT -III

OUTPUT

Enter the value of n:4

Enter values:55 44 66 11 22

given values: 55 44 66 11

Contiguous Memory Allocation (calloc())

calloc () is primarily used to allocate memory for arrays. It differs from malloc only in that
it sets memory to null characters. The declaration is as follows

Syntax of calloc()

ptr = (cast-type*) calloc(n, element-size);

Example : ptr = (float*) calloc(5, sizeof(float));

6000

0 0 0 0 0

6000 6004 6008 6012 6016

Memory is allocated for array of 5 elements of float type. The address of 1st byte is
represented by the pointer variable p. The array locations are initialized with zeros.

Reallocation of memory (realloc() )

It is highly efficient function. When given a memory pointer to a previously allocated block of
memory, realloc() changes the size of the block by deleting or extending the memory at the end
of block. If the memory cannot be extended because of other allocations, realloc() allocates a

MITS Page 22
CPDS UNIT -III

completely new block, copies the existing memory allocation to the new allocation and deletes
the old allocation. The declaration is as follows
ptr = realloc(ptr, newsize);
Example

ptr = realloc(ptr, 15*sizeof(int));

Ptr

Before

18 55 33 121 64 1 90 31 5 77

10 Integers

New
Ptr=realloc(ptr,15*sizeof(int)); elements not

ptr

18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?

15 Integers

After

MITS Page 23
CPDS UNIT -III

Program

#include<stdio.h>

#include<stdlib.h>

int main()

int *p,i,j,n;

p =(int *)malloc(3*sizeof(int)) ;

printf("Enter the 3 values:");

for(i=0;i<3;i++)

scanf("%d",(p+i));

printf("Elements before realloc:");

for(i=0;i<3;i++)

printf("\t%d",*(p+i));

p = realloc(p,5);

printf("\nEnter 2 more values:");

for(j=i;j<5;j++)

scanf("%d",(p+j));

printf("\nElements after realloc:");

for(i=0;i<5;i++)

printf("\t%d",*(p+i));

return 0;

Output

Enter the 3 values:44 55 66

MITS Page 24
CPDS UNIT -III

Elements before realloc: 44 55 66

Enter 2 more values:77 99

Elements after realloc: 44 55 66 77 99

Releasing Memory (free())

When memory locations allocated by malloc, calloc or realloc are no longer needed, they
should be freed using predefined function free. It is an error to free memory with a null pointer,
a pointer to other than the first element of an allocated bloc, a pointer that is a different type
than the pointer that allocated the memory, it is also a potential error to refer to memory after
it has been released. The function declaration is

void free(void* ptr);

Example: free(ptr);

Releasing memory does no change the value in the pointer. It still contains the address in the
heap. It is logic error to use the pointer after memory has been released.

Note : The pointer used to free memory must be of the same type as the pointer used to
allocate memory.

MITS Page 25
CPDS UNIT -III

STRINGS

A string is a series of characters treated as a unit. A string is a sequence/array of characters.


 C has no native string type; instead we use arrays of char.
 A special character, called a “null”, is important because it is the only way the functions that
work with a string can know where the string ends.
 This may be written as ‘\0’ (zero not capital ‘o’). This is the only character whose ASCII value is
zero.
 Depending on how arrays of characters are built, we may need to add the null by hand, or the
compiler may add it for us.

DECLARING AND INITIALIZING STRING VARIABLES

Declaring a String

A string variable is a valid C variable name and always declared as an array.


The general form of declaration of a string variable is,

char string_name [size];

 The size determines the number of characters in the string_name.


 When the compiler assigns a character string to a character array ,it automatically supplies a null
character(‘\0’) at the end of the string.
 The size should be equal to the maximum number of characters in the string plus one.

Declaring Strings

C has no string type. As it is defined as sequence of characters, it is stored using character


array. The storage structure, must be one byte larger than the maximum data size because there is
a delimiter at the end.
Ex : A string of 8 characters length can be declared as
char str[9];
Here str is character array or string variable
The following operations performed on character strings,

 Reading and Writing strings.


 Length of the string
 Combining Strings together.
 Copying one string to another.
 Comparing strings for equality.
 Reverse of the string

MITS Page 26
CPDS UNIT -III

 String extraction
 String reverse

Initializing String Variables

Character arrays may be initialized when they are declared. C permits a character array to be
initialized in one of the following forms,

 Initializing locations character by character.


 Partial array initialization.
 Initializing without specifying the size.
 Array initialization with a string constant.

Initializing Strings

A string can be initialized by assigning a value to it when it is defined.


Ex : char str[9] = “Good day”;

Since a sting is stored in an array of characters, we do not need to indicate the size of the array if
we initialize.
Ex : char str[] = “C Program”;

In the above case, the compiler will create an array of 10 bytes and initializes it with “C
Program” and a null character. If we now tried to store “Programming” in str array it is not
possible as the length is not sufficient. So, a string variable is initialized with a longest value.
C provides two more ways to initialize strings. A common method is to assign a string literal to a
character pointer.
Ex : char *pStr = “Hello World”;

We can also initialize a string as an array of characters. This method is not used too often
because it is so tedious to code.
Ex: char str[12] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ }

Strings and Assignment Operator


Since, the string is an array, the name of the a string is a pointer constant. So therefore a
string cannot be used as the left operand of the assignment operator.
Ex: char str1[6] = “Hello”;
char str2[6];
str1 = str2; //compile error

Initializing locations character by character

If you know all the characters at compile time, you can specify all your data within brackets:

Example,
char s[6]={‘h’,’e’,’l’,’l’,’o’,’0’};

MITS Page 27
CPDS UNIT -III

The compiler allocates 6 memory locations ranging from 0 to 5 and these locations are initialized
with the characters in the order specified. The remaining locations are automatically initialized to
null characters as shown in the below figure .

s[0] s[1] s[2] s[3] s[4] s[5]

h e l l o \0
1000 1001 1002 1003 1004 1005 Address

Figure Initializing Location Character by character

Note: It is the programmer responsibility to allocate sufficient memory so as to accommodate


NULL character at the end. Note that The ASCII values of characters are stored in the memory.

Partial Array Initialization

If the number of characters values to be initialized is less than the size of the array, then
the characters are initialized in the order from 0th location. The remaining locations will be
initialized to NULL automatically. Consider the following initialization,
char s[10]={‘h’,’e’,’l’,’l’,’o’};

The above statement allocates 10 bytes for the variable s ranging from 0 to 9 and initializes first
5 locations with the characters. The remaining locations are automatically filled with NULL as
shown in below figure 4.10.

s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
h e l l o \0 \0 \0 \0 \0
200 201 202 203 204 205 206 207 208 209 --> Address

Figure : Partial Array Initialization

Initialization Without Size

If we omit the size of the array, but specify an initial set of characters, the compiler will
automatically determine the size of the array. This way is referred as initialization without size.

char s[]={‘h’,’e’,’l’,’l’,’o’};

In this declaration, even though we have not specified exact number of characters to be used
in array s, the array size will be set of the total number of initial characters specified and appends
the NULL character.. Here, the compiler creates an array of 6 characters. The array s is
initialized as shown in Figure .

s[0] s[1] s[2] s[3] s[4] s[5]

MITS Page 28
CPDS UNIT -III

h e l l o \0
1000 1001 1002 1003 1004 1005 Address

Figure : Initializing With out size

Array Initialization with a String Constant

It takes of the following form,

char s[]=”hello”;

Here the length of the string is 5 bytes, but size is 6 bytes. The compiler reserves 5+1 memory
locations and these locations are initialized with the characters in the order specified. The string
is terminated by Null as shown in the figure 4.12.

s[0] s[1] s[2] s[3] s[4] s[5]

h e l l o \0
1000 1001 1002 1003 1004 1005 Address

Figure : Array Initializing With a String

Here are some illegal statements representing initialization of strings,

 The following declaration creates character array only not a string


char s[5]={‘h’,’e’,’l’,’l’,’o’}; //no location for appending NULL
 The following declaration is illegal.
char str[3]=“Good”; //size is less than the total characters
 We cannot separate the initialization from declaration.
char str3[5];
str3 = “Good”; Is not allowed.
 Similarly,
char s1[4] = “abc”;
char s2[4];
s2 = s1; /* Error */

Note: Observe the difference between the following ,


0 --> it is an integer zero. Occupies two bytes of memory.
‘0’ --> it is a character constant .It occupies one byte.
‘’0” --> it is a string constant. It occupies two bytes. The first byte contains
the value 0 and second byte contains \0.
‘\0’ --> it is Null character and occupies 1 byte.
“\0” --> it is a string containing a null-character. It occupies 2 bytes.

MITS Page 29
CPDS UNIT -III

Together, the string “\0” occupies two bytes.


String definition defines memory for a string when it is declared as an array in local
memory. We can also declare a string a pointer. When we declare the pointer, memory is
allocated for the pointer, no memory is allocated for the string itself.

Ex : char *Str;

String Input/Output functions


Reading a string from input
Format input statement(scanf())

char str[6];
scanf(“%s”,str);

Unformatted input statement(gets())


gets(str);

The above statements are used to read string from input and stored in the string variable str;

str[0] str[1] str[2] str[3] str[4] str[5]

h e l l o \0
1000 1001 1002 1003 1004 1005 Address

Writing a string to output


Formated output statement (printf()

printf(“%s”,str);

Unformatted output statement(putts())

puts(str);

The above statements are used to display the string on the output

Character Input/Output
1.i) getchar()
The function reads character type from the standard input. It reads one character at a time till the
user presses the enter key.

ii) putchar()

This function prints one character on he screen at a time which is read by the standard input.

MITS Page 30
CPDS UNIT -III

/* Program to accept characters through keyboard using Character I/O function */


#include <stdio.h>
void main()
{
char ch;
printf("Enter a character :");
ch = getchar();
putchar(ch);
}

Output
Enter a character : M
M

2.i) getc()
The function reads a character from the standard input or a file. It reads one character at a time
till the user presses the enter key.
ii) putc()
This function prints one character on the screen or to a file. At a time which is read by the
standard input.
void main()
{
char ch;
printf("Enter a character :");
ch = getc(stdin);
putc(ch,stdout);
}
Output
Enter a character : M
M
String Input/Output
In addition to the formatted string functions, C has two sets of string functions that read
and write strings without reformatting any data. These functions convert text-file lines to strings
and strings to text-file lines.
C provides two parallel set of functions, one for characters and one for wide characters.
They are virtually identical except for the type.
Line to String
The gets() and fgets() functions take a line from the input stream and make a null
terminated string out of it. They are therefore sometimes called line-to-string input functions.
The function declarations for get string are shown below
char* gets (char* strPtr);
char* fgets(char* strPtr, int size, FILE* sp);
The source of data for the gets is standard input; the source of data for fgets can be a file
or standard input. Both accept a string pointer and return the same pointer if the input is
successful.

MITS Page 31
CPDS UNIT -III

 If any input problems occur, such as detecting end-of-file before reading any data, they
return NULL.
 If no data were read the input area is unchanged.
 If an error occurs after some data have been read, the contents of the read-in area cannot
be determined.
Since no size is specified in gets, it reads data until it finds a new line or until the end of file. If
new line character is read, it is discarded and replaced with a null character.
The fgets function requires two additional parameters: one specifying the array size that is
available to receive the data and other a stream. It can be used with the keyboard by specifying
the stdin. In addition to new-line and end of file, the reading with stop when size-1 characters
have been read.
/* Program to determine the usage of gets and fgets*/
#include<stdio.h>
void main()
{
char name[20], add[50];
printf(“Enter your name :”);
gets(name);
printf(“Enter your address :”);
fgets(add, sizeof(add), stdin);
printf(“ Name = %s\n Address = %s”, name,add);
}

Output
Enter your name : Sukruth
Enter your address : Hyderabad
Name = Sukruth
Address = Hyderabad

String to Line
The puts/fputs functions take a null-terminated string from memory and write it to a file
or the keyboard. All change the string to a line. The null character is replaced with a newline is
puts; it is dropped in fputs. Because puts is writing to the standard output unit, usually a display,
this is entirely logical. On the other hand, fputs is assumed to be writing to a file where newlines
are not necessarily required.
The declarations for these functions are
int puts( const char* strPtr);
int fputs( const char* strPtr, FILE* sp);

/* Program to demonstrate puts/fputs usage */


#include<stdio.h>
void main()
{
char str[]= “Good Morning”;
char name[20];
puts(“Enter your name :”);

MITS Page 32
CPDS UNIT -III

gets(str);
puts(str);
fputs(str, stdout);
fputs(“\n”,stdout);
fputs(str+5, stdout);
}

Output

Enter your name : Raja


Raja
Good Morning
Morning
Operations on strings(few)

1. Finding string length


2. Copy a string
3. String reverse
4. Compare two strings
5. Concatenate (join) two strings

1. Finding string length

/*Program to calculate length of string without using string functions */


#include<stdio.h>
#include<string.h>
int main()
{
char name[50];
int i = 0;
printf("Enter a string :");
//scanf("%s",name);
gets(name);
while(name[i]!='\0')
{
i++;
}
printf("Length of the string = %d",i);
return 0;
}

OUTPUT

Enter a string :college

MITS Page 33
CPDS UNIT -III

Length of the string = 7

Explanation: Here length of the string is found by counting characters from first character to
null character(‘/0’)
Initially the variable i has 0;
i will be incremented by one every time
Loop will terminate when name[i] reaches to ‘\0’
2. Copy a string
/*Program to copy a string to another without using string functions */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i;
printf("Enter first string :");
scanf("%s",str1);
for(i = 0;str1[i]!='\0';i++)
{
str2[i] = str1[i];
}
str2[i] = ‘\0’;
printf("Given String = %s\n",str1);
printf("Copied String = %s",str2);
return 0;
}

OUTPUT

Enter first string: welcome


Given String = welcome
Copied String = welcome
Here str1 is copied into str2 character by character. Stop the copying process when str1 reaches
to ‘/0’

3. String reverse
/*Program to reverse a string without using string functions */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i=0,j=0,len=0;
printf("Enter a string :");
scanf("%s",str1);
while(str1[i++] !='\0')

MITS Page 34
CPDS UNIT -III

{
len++;
}
for(i=len-1,j=0; i>=0; i--,j++)
{
str2[j] = str1[i];
}
str2[j] = '\0';
printf("Reverse String = %s",str2);
return 0;
}

OUTPUT

Enter a string :welcome


Reverse String = emoclew

In the above program string is reversed by copying the str1 from character to first character in
the str2 from beginning . Finally put ‘\0’ in the last position of str2

4. Compare two strings

/*Program to compare two strings without using string functions */


#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i ,flag = 1;
printf("Enter first string :");
gets(str1);
printf("Enter second string :");
gets(str2);
for(i = 0; str1[i]!='\0' || str2[i]!='\0'; i++)
{
if(str1[i] != str2[i])
{
flag = 0;
break;
}
}
if(flag == 1)
printf("The given two strings are equal ");
else
printf("The given two strings are not equal ");
return 0;

MITS Page 35
CPDS UNIT -III

Enter first string :wel


Enter second string :web
The given two strings are not equal

5. Concatenate two strings


/*Program to concatenate two strings without using string functions */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i=0,j=0,len=0;
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
while(str1[i++]!='\0')
{
len++;
}
for(i=len,j=0; str2[j]!='\0'; i++,j++)
{
str1[i] = str2[j];
}
printf("Concatenated String = %s",str1);
return 0;
}
OUTPUT

Enter first string :wel


Enter second string :come
Concatenated String = welcome

6. COUNT VOWELS AND CONSONANTS


/*Program to count no.of vowels and consanants */
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
int i ,vc=0,cc=0;
printf("Enter a string :");
gets(str);

MITS Page 36
CPDS UNIT -III

for(i = 0; str[i]!='\0' ; i++)


{
if(str[i] == 'a'|| str[i] == 'e' || str[i] == 'i'|| str[i] == 'o' || str[i] == 'u')
{
vc++;
}
else
{
cc++;
}
}
printf("No.of vowels =%d ",vc);
printf("\nNo.of consonants =%d ",cc);
return 0;
}
OUTPUT
Enter a string :engineering
No.of vowels =5
No.of consonants =6

STRING MANIPULATION FUNCTIONS

C has provided a rich set of string functions. These functions make program easier and
provides the opportunity to make them more efficient when the operation is supported by
hardware instructions.
The traditional string functions have a prefix of str. The basic format is
int str…. (parameters)
The string character functions are found in the string library (string.h).
String functions
String functions Description
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 >
strcmp ( )
str2
Same as strcmp() function. But, this function negotiates case. “A” and “a”
strcmpi ( )
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

MITS Page 37
CPDS UNIT -III

strrstr ( ) Returns pointer to last occurrence of str2 in str1


strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string

String Length
The string length function strlen returns the length of a string specified as the number of
characters in the string excluding the null character. If the string is empty it returns zero. The
function declaration is as follows
int strlen(const char* string);
/* Program to find the length of string using strlen() function */
#include<string.h>
#include<stdio.h>
void main()
{
char ch[20];
int len=0;
printf("Enter a string :");
scanf("%s",ch);
len= strlen(ch);
printf("Length = %d",len);
getch();
}

Output
Enter a string : hai
Length = 3

String Copy
C has two copy functions. The first strcpy copies the contents of one string to another.
The second strncpy copies the contents of one string to another but it sets a maximum number of
characters that can be moved.

Basic String Copy


The string copy function, strcpy, copies the contents of the from string, including the null
character, to the string. The function declaration is shown below
char* strcpy(char* toStr, const char* fromStr);
If fromStr is longer than toStr, the data in memory after toStr is destroyed. So the destination
string array should be large enough to hold the sending string.
/* Program to copy string from source to destination using strcpy() function*/
#include<stdio.h>
#include<string.h>
void main()
{

MITS Page 38
CPDS UNIT -III

char str1[20],str2[20];
printf("Enter a string :");
scanf("%s",str1);
strcpy(str2,str1);
printf("Copied String = %s",str2);
}
Output
Enter a string : C Program
Copied String = C Program

Length Controlled String Copy


The function contains a parameter that specifies the maximum number of characters that
can be moved at a time. The function declaration is as follows
char* strncpy(char* toStr, const char* fromStr, int size);
In this function, size specifies the maximum number of characters that can be moved. Actually,
the operation is a little more complex.
 If the size of from string is equal to or greater than size, then size characters are moved.
 If the from string is smaller than size, the entire string is copied and then null characters
are inserted into the destination string until exactly size characters have been copied.
 If the sending string is longer than size, the copy stops after size bytes have been copied.
The string number copy functions do not insert a delimiter if the from string is longer than size.
/* Program to copy string from source to destination using strncpy() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
printf("Enter a string :");
scanf("%s",str1);
strncpy(str2,str1,5);
printf("Copied String = %s",str2);
}
Output
Enter a string : Good Morning
Copied String = Good

String Compare
C has two string compare functions. The first strcmp compares two string until unequal
characters are found or until the end of the strings reached. The second strncmp compares until
unequal characters are found, a specified number of characters have been tested or until the end
of a string is reached.
Both functions return an integer to indicate the results of the compare.
 If the two stings are equal, the return value is zero.
 If the first parameter is less than the second parameter, the return value is less than zero
i.e. negative value.

MITS Page 39
CPDS UNIT -III

 If the first parameter is greater than the second parameter, the return value is greater than
zero i.e. positive value.

Basic String Comparision


The function declared for the string compare function is as below
int strcmp(const char* str1, const char* str2);
While the string compare functions returns integer values, we can code a logical expression that
returns true or false by using the compare function and relational operators.
/* Program to compare two strings using strcmp() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
int i;
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
i=strcmp(str1,str2);
if(i==0)
printf("Strings are Equal");
else
printf("Strings are not Equal");
}
Output
Enter first string : good
Enter second string : GOOD
Strings are not Equal

Length Controlled String Comparision


The string number compare function, strncmp tests two strings for a specified maximum
number of characters (size). The function declaration is as follows
int strncmp(const char* str1, const char* str2, int size);
In this function, size specifies the maximum number of characters to be compared in the first
string. The strncmp compare logic is the same in strcmp except for the length limit.
/* Program to compare two strings using strncmp() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
int i;

MITS Page 40
CPDS UNIT -III

clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
i=strncmp(str1,str2,3);
if(i==0)
printf("Strings are Equal");
else
printf("Strings are not Equal");
}
Output
Enter first string : Good Morning
Enter second string : Good Afternoon
Strings are Equal

String Concatenate
The string concatenate functions append one string to the end of another. They return the
address pointers to the destination string. The size of the destination string array is assumed to be
large enough to hold the resulting string. If it isn’t the data at the end of the string array are
destroyed.
Basic String Concatenation
The function declaration is as follows
char* strcat(char* str1, const char* str2);
The function copies str2 to the end of str1, beginning with str1’s delimiter. That is ,the delimiter
is replaced with the first character of str2. The delimiter from str2 is copied to the resulting string
to ensure that a valid string results.
/* Program to concatenate two strings using strcat() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
strcat(str1,str2);
printf("Concatenated String = %s",str1);
getch();
}
Output
Enter first string : Data
Enter second string : Structures
Concatenated String : DataStructures

MITS Page 41
CPDS UNIT -III

Length Controlled String Concatenation


The function declaration for length controlled string concatenation is as follows
char* strncat(char* str1, const char* str2, int size);
 If the length of string2 is less than size, then the call works the same as the basic string
concatenation.
 If the length of string is greater than size, then only the number of characters specified by
size are copied and a null character is appended at the end.
 If the value of size is zero or less than zero, then both strings are treated as null, and no
characters are moved. The variable string1 is unchanged.
/* Program to concatenate two strings using strcat() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
strncat(str1,str2,6);
printf("Concatenated String = %s",str1);
getch();
}

Output

Enter first string : Data


Enter second string : Structures
Concatenated String : DataStruct

String Reverse
The reverse of a string can be done by using the function strrev. The function declaration
is as follows
char* strrev(char* string);
/* Program to reverse a string using strrev() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20];
clrscr();
printf("Enter a string :");
scanf("%s",str1);
strrev(str1);

MITS Page 42
CPDS UNIT -III

printf("Reverse String = %s",str1);


getch();
}
Output
Enter a string : world
Reverse String = dlrow

Character to String
Two string functions search for a character in a string. The first function is called strin
character strchr, it searches for the first occurrence of character from the beginning of the string.
The second string rear character strrchr, searches for the first occurrence beginning at the rear
and working toward the front.
The function declarations for these functions are shown below
char* strchr(const char* string, int ch);
char* strrchr(const char* string, int ch);
/* Program to search character using strrchr() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str[20]=”This is string”;
char *ptr, c = ‘i’;
clrscr();
ptr = strchr(ptr,c);
if(ptr)
printf(“The character %c is found in position %d”,c, ptr-string);
else
printf(“The character %c is not found”,c);
getch();
}

Output
The character i is found in position 2

Search for a Substring


We can locate a substring from the beginning of main string. There is no function to
locate a sub string starting at the rear. The function declaration of strstr is as follows
char* strstr(const char* string, const char* sub_string);
/* Program to search substring using strstr() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[40]=”American International”, str2[10]=”nation”;
char *ptr;
clrscr();

MITS Page 43
CPDS UNIT -III

ptr = strstr(str1,str2);
printf(“The substring is %s”,ptr);
}
Output
The substring is national

Array of Strings
Array of strings can be defined as the two dimensional character array. If we want to
arrange few strings in an array it can be done by declaring two dimensional character array
char names[7][20];
The above declarations says that there are 7 rows with 20 columns means 7 strings with each
string a maximum of 20 characters.
/* Program to demonstrate the array of strings */
void main()
{
char names[5][20];
int i;
printf(“Enter 5 names :”);
for(i=0; i<5; i++)
scanf(“%s”,names[i]);
printf(“Given names :\n”);
for(i=0; i<5; i++)
printf(“%s\n”,names[i]);
}

Output
Enter 5 names : Kiran Kumar Karthik Kamal Kapil
Given names :
Kiran
Kumar
Karthik
Kamal
Kapil

It is much easier and more efficient to create a array of string using pointers. Each pointer points
to individual string. In this way each string is independent, but at the same time they are grouped
together through an array.
char* days[7];
/*Program to demonstrate the array of strings */
void main()
{
char* days[7];
int i;
days[0] = “Sunday”;
days[1] = “Monday”;
days[2] = “Tuesday”;

MITS Page 44
CPDS UNIT -III

days[3] = “Wednesday”;
days[4] = “Thursday”;
days[5] = “Friday”;
days[6] = “Saturday”;
printf(“Week days : \n”);
for(i=0; i<7; i++)
printf(“%s\n”,days[i]);
}
Output
Week days :
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

MITS Page 45

You might also like