0% found this document useful (0 votes)
55 views22 pages

Unit III

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)
55 views22 pages

Unit III

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/ 22

UNIT III

STRINGS AND POINTERS


String: Introduction to String, Suppressing Input, String Taxonomy, String
operation; Pointers: Introduction to Pointers, declaring pointers variables,
Pointer expression and Pointer arithmetic, passing arguments to Function
using Pointers, Pointers and Arrays, Array of pointers; Function Pointers,
Pointers to Pointers; Drawbacks of pointers.
3.1 STRING
3.1.1 Introduction to String
String is an array of characters that is terminated by \0 (null character). This
null character indicates the end of the string. Strings are always enclosed by
double quotes (" "). Whereas, character is enclosed by single quotes.
Declaration of String: C does not support string as a data type. However, it
allows us to represent strings as character arrays. In C, a string variable is
any valid C variable name and it is always declared as an array of characters.
Syntax: char string_name[size];
The size determines the number of characters in the string name.
Note: In declaration of string size must be required to mention otherwise it
gives an error.
Ex: char str[]; // Invalid
char str[0]; // Invalid
char str[-1]; // Invalid
char str[10]; // Valid
char a[9]; //Valid
Using this declaration the compiler allocates 9 memory locations for the
variable a ranging from 0 to 8.
0 1 2 3 4 5 6 7 8

Here, the string variable a can hold maximum of 9 characters including


NULL (\0) character.
Initializing Array string
Syntax : char string_name[size]={"string"};
Note: In Initialization of the string if the specific number of character is not
initialized it then rest of all character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
Note: In initialization of the string we cannot initialized more than size of
string elements.
Ex: char str[2]={'5','+','A','B'}; // Invalid
Different ways of initialization can be done in various ways :
1 : Initializing locations character by character.
2 : Partial array initialization.
3 : Intialization without size.
4 : Array initialization with a string.
1 : Initializing locations character by character Consider the following
declaration with initialization,
Ex : char b[9]={'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R'};
The compiler allocates 9 memory locations ranging from 0 to 8 and
these locations are initialized with the characters in the order specified. The
remaining locations are automatically initialized to null characters.
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
2 : Partial Array Initialization : If the characters to be initialized is less
than the size of the array, then the characters are stored sequentially from
left to right. The remaining locations will be initialized to NULL characters
automatically
Ex : char a[10]={'R', 'A', 'M', 'A'};
The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and
initializes first four locations with the ASCII characters of 'R', 'A', 'M', 'A'.
The remaining locations are automatically filled with NULL characters (\0).
R A M A \0 \0 \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9
3 : Initialization without size : consider the declaration along with the
initialization
Ex : char b[]={'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R'};
In this declaration, the compiler will set the array size to the total number
of initial values i.e 8. The character will be stored in these memory locations
in the order specified.
b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7]
C O M P U T E R
4 : Array Initialization with a String : consider the declaration with string
initialization.
Ex : char b[ ] = "COMPUTER";
Here, the string length is 8 bytes. But, string size is 9 bytes. So the compiler
reserves 8+1 memory locations and these locations are initialized with the
characters in the order specified. The string is terminated by \0 by the
compiler.
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
The string “COMPUTER” contain 8 characters, because it is a string. It
always ends with null character. So, the array is 9 bytes (i.e string length+1
byte for null character).
Reading and Writing Strings : The "%s" control string can be used in
scanf() statement to read a string from the terminal and the same may be used
to write string to the terminal in printf() statement.
Example : char name[10];
scanf("%s",name);
printf("%s",name);
Example:
#include <stdio.h>
void main ()
{
char ch[13]={'c','p','r','o','g','r','a','m','m','i','n','g','\0'};
char ch2[13]="cprogramming";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
}
Output
Char Array Value is: cprogramming
String Literal Value is: cprogramming
Example:
#include <stdio.h>
void main(){
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
String Input/output Functions
The strings can be read from the keyboard and can be displayed onto the
monitor using various functions.
The various input and output functions that are associated with can be
classified as
I/O Functions

Formatted I/O Unformatted I/O


Input
Input getc()
scanf() getchar()
fscanf() gets()
getch()
Output getche()
printf() Output
fprintf() putc()
putchar()
puts()

Unformated I/O Functions


1: getc() function : This function is used to accept a single character from
the standared input to a character variable.
Syntax : character variable=getc();
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getc();
printf("The Character is: %c\n",ch);
}
Output :
Enter any character: a
The Character is: a
2: getchar() function : A single character can be given to the computer using
‘C’ input library function getchar().
Syntax : char variable=getchar();
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getchar();
printf("The Character is: %c\n",ch);
}
Output :
Enter any character: a
The Character is: a
3: gets() function : The gets() function is used to read the string (String is a
group of characters)
Syntax : gets(char type of array variable);
Example:
#include<stdio.h>
#include<conio.h>
void main() {
char str[40];
printf("Enter String name:");
gets(str);
printf("The string name: %s:",str);
}
Output :
Enter string name: subbareddy
The string name: subbareddy
4: getch() function : The getch function reads a single character directly
from the keyboard, without echoing to the screen.
Syntax : int getch();
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char c;
printf("Enter a Character: ");
c=getch();
printf("Entered Character: %c",c);
}
Output :
Enter a Character:
Entered Character: j
5: getche() function : The getche() function reads a single character from
the keyboard and echoes it to the current text window.
Syntax : int getche();
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char c;
printf("Enter a Character: ");
c=getche();
printf(“Entered Character: %c“,c);
}
Output :
Enter a Character: j
Entered Character: j
6: putc() function : This function is used to display a single character in a
character variable to standared output device, monitor.
Syntax : putc(character variable);
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getc();
printf("The Character is: ");
putc(ch);
}
Output :
Enter any character: a
The Character is: a
7: putchar() function :The putchar() function is used to display one
character at a time on the standard output device, monitor.
Syntax : putchar(character varaiable);
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getchar();
printf("The Character is: ");
putchar(ch);
}
Output :
Enter any character: a
The Character is: a
8: puts() function: The puts() function is used to display the string to the
standard output device (Monitor).
Syntax : puts(char type of array variable);
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char str[40];
puts("Enter String name: ");
gets(str);
puts("The string name: ");
puts(str);
}
Output :
Enter String name: subbareddy
The string name: subbareddy
3.1.2 String Operations/ String Handling Functions
1 : strlen(string) – Finding String Length : This function is used to
count and return the number of characters present in a string.
Syntax : var=strlen(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char name1[]="JBREC";
char name2[]="JBRECECE ";
int len1,len2;
len1=strlen(name1);
len2=strlen(name2);
printf("The string length of %s is: %d\n",name1,len1);
printf("The string length of %s is: %d",name2,len2);
}
Output :
The string length of JBREC is: 5
The string length of JBRECECE is: 8
2 : strcpy(string1,string2) – Copying String : This function is used to
copy the contents of one string to another string.
Syntax : strcpy(string1,string2);
Where string1 is the destination string and string 2 is the source string. i.e
the contents of string2 is assigned to the contents of string1.
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="REDDY";
char str2[10];
strcpy(str2,str1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s\n",str2);
}
Output :
The string1 is : REDDY
The string2 is : REDDY
3 : strlwr(string) – Converting String to LowerCase : This function is
used to converts upper case letters of the string in to lower case letters.
Syntax : strlwr(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="JBREC";
printf("The String is : %s\n",str);
printf("The lowercase is : %s\n",strlwr(str));
}
Output :
The String is : JBREC
The lowercase is : jbrec
4 : strupr(string) – Converting String to UpperCase : This function is
used to converts lower case letters of the string in to upper case letters.
Syntax : strupr(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="jbrec";
printf("The String is : %s\n",str);
printf("The Uppercase is : %s\n",strupr(str));
}
Output:
The String is : jbrec
The Uppercase is : JBREC
5 : strcmp(string1,string2) – String Comparision : This function is used
to compares two strings to find out whether they are same or different. If
the two strings are same strcmp() returns a value zero. If they are not
equal, it returns the numeric difference between the first non-matching
characters.
Syntax : strcmp(string1,string2);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="reddy";
char str2[]="reddy";
int val=strcmp(str1,str2);
if(val==0)
printf(“The two Strings are equal”);
else
printf(“The two Strings are not equal”);
}
Output:
The two Strings are equal
6: strcat(string1,string2) – String Concatenation : This function is used
to concatenate or combine, two strings together and forms a new
concatenated string.
Syntax : strcat(sting1,string2);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="Hai";
char str2[]="Hello";
printf("The First String is: %s\n",str1);
printf("The second String is: %s\n",str2);
strcat(str1,str2);
printf("The concatenated String is: %s",str1);
}
Output:
The First String is: Hai
The second String is: Hello
The concatenated String is: HaiHello
7 : strrev(string) - String Reverse : This function is used to reverse a
string. This function takes only one argument Syntax : strrev(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="Hello";
printf("The Original String is: %s\n",str);
printf("The Reversed String is: %s",strrev(str));
}
Output:
The Original String is: Hello
The Reversed String is: olleH
8 : strncpy(str,position,length) -Extracting Substring from a String:
Copies a substring from a given input string
Syntax : strncpy(str,position,length);
Example:
#include <stdio.h>
#include <string.h>
void main(){
char originalString[] = "Hello, World!";
char substring[10];
int start = 7;
int length = 5;
strncpy(substring, originalString + start, length);
printf("Original String: %s\n", originalString);
printf("Substring: %s\n", substring);
}
Output:
Original String: Hello, World!
Substring: World
3.1.3 Suppressing Input
The scanf() function can be used to read a field without assigning it to any
variable. This is done by preceding that field's format code with a *. For
example, consider the example below:
scanf("%d*c%d", &hr, &min);
The time can be read as 9:05. Here the colon would be read but not assigned
to anything. Therefore, assignment suppression is particularly useful when
part of what is input needs to be suppressed.
Using a Scanset
Scanset is used to define a set of characters which may be read and assigned
to the corresponding string. Scanset is defined by placing the characters
inside square brackets prefixed with a %, as shown in the example below:
%[aeiou]
When we use the above scanset, scanf () will continue to read characters
and put them into the string until it encounters a character that is not
specified in the scanset. For example, consider the code given below.
#include <stdio.h>
void main()
{
char str[10];
printf("\n Enter string: ");
scanf("%[aeiou]",str );
printf("The string is: %s",str);
}
The code will stop accepting a character as soon as the user enters a
character that is not a vowel.
However, if the first character in the set is a ^ (caret symbol), then scanf ()
will accept any character that is not defined by the scanset. For example, if
you write
scanf("%[^aeiou]",str);
Then, str will accept characters other than those specified in the scanset,
i.e., it will accept any non-vowel character. However, the caret and the
opening bracket can be included in the scanset anywhere. But they have a
predefined meaning only when they are included as the first character of the
scanset. So if you want to accept a text from the user that contains caret and
opening bracket then make sure that they are not the first characters in the
scanset. This is shown in the following example.
scanf("% [0123456789.^ []()_+-$%&*]",str);
vs In the given example, str can accept any character enclosed in the
opening and closing square brackets (including and [)
The user can also specify a range of acceptable characters using a hyphen.
This is shown in the statement given below:
scanf("%[a-z]", str);
Here, str will accept any character from small a to small z. Always
remember that scansets are case sensi- tive. However, if you want to accept
a hyphen then it must either be the first or the last character in the set.
To better understand scanset try the following code with different inputs
#include <stdio.h>
void main()
{
char str[10];
printf("\n Enter string: ");
scanf("%[A-Z]", str);
printf("The string is: %s", str);
}
3.1.4 String Taxonomy
Taxonomy means hierarchical description of something & a collection of
alphabet & symbols are recognized as string in c language. Hence string
taxonomy means details of different type of strings and their manipulation.

Fixed-length string: 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 string: 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 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 string: 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 string: 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.

3.2 POINTERS
3.2.1 Introduction to Pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is
also known as indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Defining a pointer
int n = 50;
int* p = &n; // Variable p of type pointer is pointing to the address of
the variable n of type integer.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of
number variable, i.e., fff4. The value of number variable is 50. But the
address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer
variable p.
Example:
#include<stdio.h>
void main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
}
Output
Address of number variable is fff4
Value of p variable is 50
3.2.2 Pointer expression 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.
int num1=2, num2= 3, sum=0, mul=0, div=1;
int *ptrl, *ptr2;
ptrl = &num1;
ptr2 = &num2;
sum = *ptrl + *ptr2;
mul = sum* *ptrl;
*ptr2 +=1;
div = 9 + *ptr1/*ptr2 - 30;
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) ++

3.2.3 Passing arguments to Function using Pointers


While using pointers to pass arguments to a function, the calling function
must pass addresses of the variables as arguments and the called function
must dereference the arguments to use them in the function body for
processing.
To use pointers for passing arguments to a function, the programmer must
do the following:
• Declare the function parameters as pointers
• Use the dereferenced pointers in the function body
• Pass the addresses as the actual argument when the function is called.
Example:
#include <stdio.h>
void sum (int *a, int *b, int *t);
void main()
{
int num1, num2, total;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum (&num1, &num2, &total);
printf("Total = %d", total);
}
void sum (int *a, int *b, int *t){
*t = *a + *b;
}
Output
Enter the first number: 2
Enter the second number: 3
Total = 5
3.2.4 Pointers and Arrays
An array occupies consecutive memory locations.

If we have an array declared as int arr[] = {1, 2, 3, 4, 5}; then in memory


it would be stored as shown in Figure

Array notation is a form of pointer notation. The name of the array is the
starting address of the array in memory. It is also known as the base address.
In other words, base address is the address of the first element in the array
or the address of arr [0] . Now let us use a pointer variable as given in the
statement below.
int *ptr;
ptr = &arr [0];
Here, ptr is made to point to the first element of the array.
If ptr originally points to arr [2], then ptr++ will point to the next element,
i.e., arr [3].

Example:
#include <stdio.h>
void main()
{
int arr[]={1,2,3,4,5};
printf("\n Address of array = %p %p %p", arr, &arr[0], &arr);
}
Output
Address of array = 0x7ffd36139bf0 0x7ffd36139bf0 0x7ffd36139bf0
3.2.5 Passing an Array to Functions
An array can be passed to a function using pointers. For this, a function that
expects an array can declare the formal parameter in either of the two
following ways:
func (int arr[]); OR func (int *arr);
Example
#include <stdio.h>
#include <conio.h>
void read_array (int *arr, int n);
void print_array(int *arr, int n);
void find_small (int *arr, int n, int *small, int *pos);
void main(){
int num[10], n, small, pos;
printf("\n Enter the size of the array: ");
scanf("%d", &n);
read_array (num, n);
print_array (num, n);
find_small (num, n, &small, &pos);
printf("\n The smallest number in the array is %d at position %d", small,
pos);
getch();
}
void read_array(int *arr, int n)
{
int i;
printf("\n Enter the array elements: ");
for (i=0; i<n;i++)
scanf("%d", &arr[i]);
}
void print_array (int *arr, int n)
{
int i;
printf("\n The array elements are: ");
for (i=0;i<n;i++)
printf("\t %d", arr[i]);
}
void find_small (int *arr, int n, int *small, int *pos)
{
int i;
for (i=0;i<n;i++){
if (* (arr+i) < *small){
* small = * (arr+i);
*pos = i;
}
}
}
Output
Enter the size of the array: 5
Enter the array elements: 1 2 3 4 5
The array elements are: 1 2 3 4 5
The smallest number in the array is 1 at position 0
3.2.6 Function Pointers
In order to declare a pointer to a function we have to declare it like the
prototype of the function except that the name of the function is enclosed
between parentheses () and an asterisk (*) is inserted before the name. The
syntax of declaring a function pointer can be given as
return_type (*function_pointer_name) (argument_list);
Initializing a Function Pointer
As in case of other pointer variables, a function pointer must be initialized
prior to use. If we have declared a pointer to the function, then that pointer
can be assigned the address of the correct function just by using its name.
Like in the case of an array, a function name is changed into an address
when it's used in an expression. It is optional to use the address operator
(&) in front of the function name.
For example, if fp is a function pointer and we have a function add () with
prototype given as
int add (int, int);
Then writing fp = add; initializes the function pointer fp with the address of
add ().
Calling a Function Using a Function Pointer
When a pointer to a function is declared, it can be called using one of two
forms:
(*func) (1,2); OR func (1,2);
Example:
#include<stdio.h>
#include<conio.h>
void print(int n);
void *fp(int);
void main(){
fp = print;
(*fp) (10);
fp (20);
getch();
}
void print(int value){
printf("\n %d", value);
}
Output
10
20
Comparing Function Pointers
Comparison operators such as = = and != can be used the same way as usual.
Consider the code given below which checks if fp actually contains the
address of the function print (int).
if (fp >0) // check if initialized
{
if (fp == print)
printf("\n Pointer points to print ");
else
printf("\n Pointer not initialized!");
}
Passing a Function Pointer as an Argument to a Function
A function pointer can be passed as the calling argument of a function. This
is in fact necessary if you want to pass a pointer to a callback function. The
following code shows how to pass a pointer to a function which returns an
int and accepts two int values.
Note that in the program below, the function operate calls the functions add
and subtract with the following line:
result = (*operate_fp) (num1,num2);
#include <stdio.h>
int add (int, int);
int sub (int, int);
int operate (int (*operate_fp) (int, int), int, int);
void main()
{
int result;
result = operate (add, 9, 7);
printf ("\n Addition result = %d", result); n
result = operate (sub, 9, 7);
printf ("\n Subtraction = %d", result);
}
int add (int a, int b)
{
return (a + b);
}
int sub (int a, int b)
{
return (a - b);
}
int operate (int (*operate_fp) (int, int), int a, int b)
{
int result;
result = (*operate_fp) (a, b);
return result;
}
Output
Addition = 16
Subtraction = 2
3.2.7 Pointers to Pointers
In C language you are also allowed to use pointers that point to pointers.
The pointers in turn, point to data (or even to other pointers). To declare
pointers to pointers, just add an asterisk (*) for each level of reference. For
example, if we have:
int x = 10
int *px; //pointer to an integer
int **ppx; // pointer to a pointer to an integer
px = &x;
ppx = &px;
Assume that the memory location of these variables is as shown in
Figure

Now if we write,
printf("\n %d", **ppx);
then it will print 10, the value of x.
3.2.8 Drawbacks of pointers
 Errors: Pointers can cause errors such as segmentation errors,
unrequired memory access, and memory corruption.
 Memory leaks: Pointers can lead to memory leaks.
 Difficulty to understand: Pointers can be difficult to understand.
 Slower than variables: Pointers are generally slower than variables.
 Dangling pointers: Dangling pointers can create errors that are
difficult to diagnose.
 Undefined behavior: Undefined behavior can occur when two pointers
point to the same memory location and one of the pointers is freed.
 Garbage values: Garbage values in memory are values that cannot be
accessed.
 Pointer arithmetic: Pointer arithmetic can cause security flaws. For
example, if a pointer is adjusted across the bounds of an object, the
system cannot detect the error.
 Null pointer dereferences: Excessive pointer usage can lead to null
pointer dereferences. These usually result in the process failing, unless
exception handling is available.
 Wild pointers: A wild pointer is a pointer that has not been initialized
to a memory location before it is used. Using a wild pointer can lead
to unexpected behavior or data corruption.

You might also like