0% found this document useful (0 votes)
9 views18 pages

Pop(Bpops103) Module 4

Module 4 covers strings and pointers in C, defining strings as variable-length data stored in character arrays, with distinctions between string literals and string variables. It explains how to declare, initialize, and manipulate strings, including operations like printing, reading, and various string functions such as strcpy, strlen, and strcat. Additionally, it discusses limitations of string assignments and the differences between fixed-length and variable-length strings.

Uploaded by

pallavikkotikall
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)
9 views18 pages

Pop(Bpops103) Module 4

Module 4 covers strings and pointers in C, defining strings as variable-length data stored in character arrays, with distinctions between string literals and string variables. It explains how to declare, initialize, and manipulate strings, including operations like printing, reading, and various string functions such as strcpy, strlen, and strcat. Additionally, it discusses limitations of string assignments and the differences between fixed-length and variable-length strings.

Uploaded by

pallavikkotikall
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/ 18

First Year Engineering, Sub Name: POP Code: 22POP13 Module No.

: 4

MODULE 4:

Strings and Pointers:


String Concept:
Definition: String is a variable length data stored in a character array.
Example: “hello”, “India”
I. C- strings
➢ In C a string is a data structure based on an array of char.
➢ A string is a sequence of elements of the char data type.
➢ There is no separate data-type called string in C language.
➢ As strings are variable-size data we have to represent them using characterArrays.
Example string is:

R A J E S H \0 Delimiter ‘\0’
0 1 2 3 4 5 6 indicates end of
string

Strings in C are classified into two types:

1. String literals
2. String variables

String literals are also known as string constants, is a sequence of characters enclosed by double quotation
marks is called string literals. A string literal is a constant its valuecannot be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.

String variables are nothing but character array. Following syntax and examplesillustrates declaring string
variables.
Example: char array_name[ ]= “raj”

How string is stored?


➢ A string, even a literal one is very similar to an array of characters.
➢ The only difference between array of char and string is that, a string must end
with null character (\0).
➢ If you use a literal string in a program, it is stored in consecutive bytes in memory and
compiler places the null character at the end.
➢ Below fig shows storage for literal string “CBIT”
C B I T \0

1
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Declaring string variables: A string is declared like an array of characters.

Syntax: char string_name[size];

Ex: char name[21];


Size 21 means it can store up to 20 characters plus the null character. Entire storage location name is divided
in to 21 boxes called bytes, each of which holds one character. Each character is element of data type char.

Initializing the string in the declarationchar


first[10]={‘t’,’a’,’b’,’l’,’e’,’\0’}; char
second[10]=”table”;

Difference between a single character string and a single character array is:
Single character array takes 1 byte where as single character string occupies twobytes as shown below:

A \0 Single character string

‘A’ 25

Limitations of Strings: One string variable cannot be directly assigned to anotherstring as in the case of
ordinary scalar variables.
Let us say int a=10, b;
b=a; /* is perfectly valid */
But take an example of string initialization:
char name1[ ] = “hello”;
char name2[10 ];
name2=name1; /* This initialization is invalid */

But this initialization can be done using a loop and assigning individual characters of
name1 to name2 as shown below:
void main( )
{
int i;
char name1[ ]= “hello”;

2
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

char name2[5];
for ( i=0; i<5;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}

Printing and reading a string: Token oriented input/output function


Printing a string using printf: We can use printf function with %s format specifier to
print a string on to the monitor. The %s is used to display an array of characters that is
terminated by null character.
Example:
(1) char name[10]=”Andy”;
printf(“the name is %s\n”,name);
o/p: the name is Andy

(2) char name[ ]= “ MANGALORE”;


printf(“%s”, name);
printf (“%9.6s”, name);
printf(“%-10.3s”, name);

M A N G A L O R E %s prints entire string

%9.6s prints first 6 characters out of 9


M A N G A L
characters

Prints first 3 characters but in left


M A N
justified manner because of (- ) sign

Printing a string using puts():


We can also use puts() to print the string on screen.
Syntax: puts(string);

3
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Example:
#include<stdio.h>
int main()
{
char a[]= “akash”;
puts(a);
}
o/p: akash
Reading a string using scanf( )
It uses string conversion specifier %s to accept a string data. Following example illustrates it:
char name[20];
scanf(“%s”, name);
Note: while reading strings we needn’t specify address of operator (&) as the character array itself is an
address (i.e name itself is base address of array in the above example)

Disadvantage of reading strings using scanf( ) function is multiple words strings cannot be read. For
example say we have to read NEW DELHI, following scanf( ) reads only NEW and stops.

scanf(“%s”, name);say

input is
N E W D E L H I

Only part of a string (NEW) is read an d second half (DELHI) is ignored.

N E W

So instead of scanf() we can use gets()

Example:
#include<stdio.h>
int main()
{
char a[10];
printf("enter name");
gets(a);
printf("\nname: ");
printf("%s",a);
}

4
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Extra:

Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion code %[ ], which
specifies the type of characters that can be accepted by scanf ( ) function.
For Example say we have to accept only 0-9 digits in a string then edit set code can be
used as follows:
char name[20];
scanf(“%[0123456789]”, name)

Example strings that will be read by above statement are:


12345, 123, 567, 7890 etc.

NOTE: Suppose we want to skip particular set of characters in a string, then we have to
use:
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)

This function skips all Capital alphabets from a string.


Say string is APPLE, banana, Mango
Accepted words are: banana, ango

String taxonomy
• Strings in Pascal is different from strings in C:
• We can store a string either in fixed length format or variable length format.

Fixed-length strings:
When storing a string in a fixed-length format, you need to specify an appropriate size for the string variable. If
the size is too small, then you will not be able to store all the elements in the string. On the other hand, if the
string size is large, then unnecessarily memory space will be wasted.

Variable-length strings:
A better option is to use a variable length format in which the string can be expanded or contracted to
accommodate the elements in it. For example, if you declare a string variable to store the name of a student. If a
5
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

student has a long name of say 20 characters, then the string can be expanded to accommodate 20 characters.
On the other hand, a student name has only 5 characters, then the string variable can be contracted to store only
5 characters. However, to use a variable-length string format you need a technique to indicate the end of
elements that are a part of the string. This can be done either by using length-controlled string or a delimiter.

Length-controlled strings:
In a length-controlled string, you need to specify the number of characters in the string. This count is used by
string manipulation functions to determine the actual length of the string variable.

Delimited strings:
In this format, the string is ended with a delimiter. The delimiter is then used to identify the end of the string.
For example, in English language every sentence is ended with a full-stop (.). Similarly, in C we can use any
character such as comma, semicolon, colon, dash, null character, etc. as the delimiter of a string.
However, null character is the most commonly used string delimiter in the C language. You must be having
some confusion when we use the term string and character array. Basically a string is stored in an array of
characters. If we are using the null character as the string delimiting character then we treat the part of the array
from the beginning to the null character as the string and ignore the rest.

Operations on string:

There are carious operations which can be performed on strings without using build in library functions.
Those operations are listed below.
1. Converting Characters of a String into Upper Case
2. Converting Characters of a String Into Lower Case
3. Appending string to another string
4. Comparing 2 strings
5. Finding length of the string.

6
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

1. Converting Characters of a String into Upper Case


We have already seen that in memory the ASCII codes are stored instead of the real value. The ASCII code for
A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97 to 123. So if we have to convert a lower
case character to upper case, then we just need to subtract 32 from the ASCII value of the character.

2. Converting Characters of a String Into Lower Case


If we have to convert an upper case character into lower case, then we just need to add 32 to its ASCII value.
Figure 13.8 shows an algorithm that converts characters of a string into lower case.

7
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

3. Appending string to another string


often it is useful to concatenate or join two strings together. The concatenation function is used to join
two strings together. The resulting string has only one null character at the end.
Example:
void my_strcat(char str1[], char str2[])
{
int i=0,j=0;
while (str1[i]!='\0')
i++;
while (str2[j]!='\0')
{
str1[i++]=str2[j++];
}
str1[i++]='\0';
printf("concatinated string= %s", str1);
}

8
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

4. Comparing 2 strings
A compare function is used to compare two strings. It takes the two strings as a parameter and returns
an integer value based on the relationship between two strings.

5. Finding length of the string.


the string length function can be used to find the length of the string.

String manipulation function (Miscellaneous string and character functions)


C library supports a large number of string handling functions that can be used to carry out many of the
string manipulations and are stored in header file “string.h”. Following are the most commonly used string
handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
3. strcmp( ) compare two strings
4. strcat( ) concatenates two strings
5. strncpy( ) copies left most n characters of source to destination
6. strncmp( ) compares left most of n characters of source to destination.

9
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

1. strcpy( ): It is possible to assign a value to a string variable using strcpy( ). It allows


us to copy a string from one location to another. The string to be copied can be literal or
string variable. The general form of call to strcpy is
strcpy(dest,source);
Strcpy() function has two parameters. The first is the dest, a string variable whose value is going to be
changed. The second is the source the string literal or variable which is going to be copied to the destination.

Ex: char first[14];


char last[14];
strcpy(first,”ravi kumar”);
strcpy(last,first);
After two calls to strcpy, first and last each has a value “ravi kumar”
A call to strcpy can be used to copy just part of a string. Either or both of the parameterscan refer to addresses
past the beginning of their strings.
Ex: char name[20]=”RAVI KUMAR”; char
newname[20]=”LEE DAVIS”;
strcpy(name+5,newname+4);

strcpy() does not check to see whether there is room for the resulting string at the specified location. If there
is no room, it copies characters on top of whatever variables follow in memory. This may destroy the
contents of other variables.

2. strlen():the string length function can be used to find the length of the string inbytes.
It takes the form
length=strlen(str);
syntax: strlen(string);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”SGBIT” ;
length=strlen(str); //5
str='\0';
length=strlen(str); //0

10
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

3. strcmp( ): A strcmp() is used to compare two strings. It takes the two strings as a
parameter and returns an integer value based on the relationship between two strings.
General form of call to
strcmp(srt1,str2)
result=strcmp(first,second);
result>0 if first> second
result=0 if first==second
result<0 if first<second
Ex: int res;
res=strcmp(“cat”,”car”); //res>0
res=strcmp(“pot”,”pot”);//res=0
res=strcmp(“big”,”little”); //res<0

4. strcat( ): often it is useful to concatenate or join two strings together. The strcat
function is used to join two strings together. The resulting string has only one null
character at the end.
General form of a call to strcat( )
strcat(first, second);
After the call, first contains all the characters from first, followed by the ones from
second up to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it
doesn’t find a null character, strcat continues copying bytes from memory until it finds
null character. The programmer must check to make sure that the resulting string fits in
the variable.

Ex: char first[30]=”computer”;


char second[15]=” programming”;
strcat(first,second); //computer programming

11
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

5. strncmp( ): The strncmp function compares up to specified number of characters from


the two string, starting at the address specified, and returns integer representing the
relationship between the compared string sections. It compares the character by
character until it finds a null character or characters that are different or until it has
compared number of characters.
General form of call to strncmp()
strncmp(firstaddress, secondaddress, numchars);

Ex: char first[30]=”string”;


char second[10]=”stopper”;
int n;
if(strncmp(first,second,4)==0)
printf(“first four characters are alike\n”);
else if(strncmp(first,second,4)<0)
printf(“first four characters of first string are less\n”);
else
printf(“first four characters of first string are greater\n”);

6. strncpy( ): The strncpy function allows us to extract a substring from one string and
copy it to another location.
General form of call to strncpy()
strncpy(dest, source, numchars);
The strncpy function takes three parameters. Here this statement copies the numchars
of the source string in to dest string. Since numchar does not include null character , we
have to place it explicitly in the source string.
Ex: char source[20]=”computer world”;
char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com

12
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};

Pointers
Pointers: A pointer is a variable that holds the address of another variable. The pointer variablecontains
only the address of the referenced variable not the value stored at that address.

Some of the advantages of using pointers are as follows


1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures such asstructures,
linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in memory

Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memoryis not
available at run time to store pointers.

Pointer uses two basic operators


1. The address operator (&): It gives address of an object
2. The indirection operator (*):It is used to accesses the object the pointer points to.

Declaring a pointer variable:


The general syntax of declaring pointer variable is

Datatype *ptrname;

Data type: It specifies the type of the pointer variable that you want to declare like (int, float,char, double
or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the name of
the pointer variable.

Example: int *p; // declares a pointer variable p of integer type


float *temp;// declares a pointer variable temp of float data type

13
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of othervariables to them.
Syntax
Datatype *ptrname = expression;
Where,
Datatype: It can be any basic data type,
ptrname is a pointer variable,
expression can be any constant value or any variable containing value.
Example:
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable.
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp

program to illustrate declaration and initialization

#include<stdio.h>void
main()
{
int *ptr; / /declaration of pointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200

Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage cells,
each cell has an address. When you declare a variable, the operating system allocates memory according to
the size of the data type of that variable. In this memory location, the value of the variable is stored.

Example : int a=100;

This statement request the operating system to allocate two bytes of space in memory and stores 100 in
that location.
a ------------ →variable name

100 ---
---------→value of the variable

1500----------- → the address of the memory location

14
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

By using the address of (&) operator, you can determine the address of a variable.

#include<stdio.h>
void main()
{
int a=100,*ptr1; float
b=12.6, *ptr2;ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f\n”,ptr2,*ptr2);

}
Output: the address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000

POINTER EXPRESSIONS AND POINTER ARITHMETIC


Like other variables, pointer variables can also be used in expressions. For example, if ptr1 and
ptr2 are pointers, then the following statements are valid.

• In C, the programmer may add or subtract integers from pointers.


• We can also subtract one pointer from the other.
• We can also use short hand operators with the pointer variables as we use with other
variables.
• C also allows to compare pointers by using relational operators in the expressions.
For example, p1 > p2, p1 == p2, and p1! = p2 are all valid in C.
• When using pointers, unary increment (++) and decrement (- -) operators have greater
precedence than the dereference operator (*).
• Both these operators have a special behaviour when used as suffix.
• In that case the expression is evaluated with the value it had before being increased.
• Therefore, the expression *ptr++ is equivalent to * (ptr++) as ++ has greater operator
precedence than *.
• Therefore, the expression will increase the value of ptr so that it now points to the next
memory location.
• This means the statement *ptr++ does not perform the intended task.
• Therefore, to increment the value of the variable whose address is stored in ptr, you
should write (*ptr)++.

15
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Let us now summarize the rules for pointer operations:


• A pointer variable can be assigned the address of another variable (of the same type).
• A pointer variable can be assigned the value of another pointer variable (of the same type).
• A pointer variable can be initialized with a null value.
• Prefix or postfix increment and decrement operators can be applied on a pointer variable.
• An integer value can be added or subtracted from a pointer variable.
• A pointer variable can be compared with another pointer variable of the same type using
relational operators.
• A pointer variable cannot be multiplied by a constant.

Types of pointers:
1. NULL POINTER:
• We have seen that a pointer variable is a pointer to some other variable of the same data type.
• However, in some cases we may prefer to have null pointer which is a special pointer that does not
point to any value.
• This means that a null pointer does not point to any valid memory address.
• To declare a null pointer you may use the predefined constant NULL, which is defined in several
standard header files including <stdio.h>, <stdlib.h>, and <string.h>.
• After including any of these files in your program, write
int *ptr = NULL;
• You can always check whether a given pointer variable stores address of some variable or contains a
NULL by writing:
if (ptr == NULL)
{
Statement block;
}

• You may also initialize a pointer as a null pointer by using a constant 0, as shown below.
int ptr;
ptr = 0;

2. GENERIC POINTERS
• A generic pointer is a pointer variable that has void as its data type.
• The void pointer, or the generic pointer, is a special type of pointer that can be used to point to variables
of any data type.
• It is declared like a normal pointer variable but using the void keyword as the pointer's data type.
• For example, void *ptr;
• In C, since you cannot have a variable of type void, the void pointer will therefore not point to any data
and thus cannot be dereferenced.
• You need to type cast a void pointer (generic pointer) to another kind of pointer before using it.
• Generic pointers are often used when you want a pointer to point to data of different types at different
times.
For example,

16
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

#include <stdio.h>
int main()
{
int x=10;
char ch = 'A';
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %", * (int*) gp);
gp = &ch;
printf("\n Generic pointer now points to the character = %c", * (char*) gp) ;
}

Passing arguments to the function using pointers


Pointers and functions (call by reference) arguments:
The call by reference method allows you to copy the addresses of actual arguments of the calling function
to the formal arguments of the called function. In this method the pointers are passed as arguments to the
functions. When you change the values in the functions, the original values of the actual parameters are
also changed. Following program illustrate use of call by reference.

Example 1
#include<stdio.h>
void swap(int *a, int *b);void
main()
{
int x, y;
x=100;
y=200;
printf(“before swap: x=%d\n y=%d\n”, x,y);
swap(&x, &y);
printf(“after swap: x=%d\n, y=%d\n”, x, y);
}
void swap(int *a, int *b)
{
int temp;temp=*a;
*a=*b;
*b=temp;
}

Output:
Before swap: x=100
y=200
After swap: x=200
y=100

17
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4

Example 2
#include <stdio.h>
#include <conio.h>
void sum (int *a, int *b, int *+);
int main()
{
int num1, num2, total;
printf("\n Enter the first number: ");
scanf ("%d", &num1);
printf("\n Enter the second number: ");
scanf ("%d", &num2); sum (&num1, &num2, &total);
printf ("\n Total = %d", total);
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}

18

You might also like