BPOPS103/203 Module 4 Notes
BPOPS103/203 Module 4 Notes
Strings
String variable:
A string is an array of characters. Any group of characters defined between
double quotation marks is called a constant string.
String in C programming is a sequence of characters terminated with a null character „\0‟.
Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a unique character „\0‟.
Example:
“Good Morning Everybody”
Character strings are often used to build meaningful and readable programs.
A string variable is any valid C variable name and is always declared as an array.
The reason that state had to be 10 elements long is that the string KARNATAKA contains 10
characters and one element space is provided for the null terminator.
Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, text);
Can be used to display the entire contents of the array name.
String functions:
C library supports a large number of string functions. The list given below depicts the
string functions
Function Action
strcat( ) concatenates two strings
strcmp( ) compares two strings
strcpy( ) copies one string with another
The strcat function joins two strings together. The general form is
strcat(string1,string2);
string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Example
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
The output will be: after before
The strcmp function compares two strings identified by the arguments and has a value 0
if they are equal.
The general form is :
strcmp(string1,string2);
String1 and string2 may be string variables or string constants.
On comparing the return value be determined basis the strings setup as shown below.
The function returns a definite value that may be either 0, >0, or <0. In this function, the two
values passed are treated as case sensitive means „A‟ and „a‟ are treated as different letters.
The values returned by the function are used as:
i) 0 is returned when two strings are the same
ii) If str1<str2 then a negative value is returned
iii) If str1>str2 then a positive value is returned
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;
Function strrev()
If you want to reverse any string without writing any huge or extensive program manually,
then you can use this function. The rev in the strrev() stands for reverse and it is used to
reverse the given string. Function strrev() is used to reverse the content of the string. Strrev
function is used to check the nature of the string, whether the given string is a palindrome or
not. Several other uses and applications are also present in the string reverse function. One of
its uses is given below:
#include<stdio.h>
#include<string.h>
int main()
{
char temp[20]=”Reverse”;
printf(“String before reversing is : %s\n”, temp);
printf(“String after strrev() :%s”, strrev(temp));
return 0;
}
Output
Enter a character=A
You typed an alphabet
6. isupper()
8. toupper()
This function converts lowercase alphabet into uppercase alphabet.
9. tolower()
This function converts an uppercase alphabet into lowercase alphabet.
Program to use of islower,isupper,tolower(),toupper().
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}
Output
Enter an alphabet=A
Now alphabet=a
Pointers:
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. As we know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which will print the address of
the variables defined:
#include <stdio.h>
int main ()
{
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Basics of pointers:
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. In other words, a pointer is a variable that represent the location (rather
than the value) of a data item, such as a variable or an array element. It is a variable that holds a
memory address. This address is the location of another variable or an array element in memory.
For example, if one variable contains the address of another variable, the first variable is said to
point to the second.
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
In the above example, ptr is the name of our variable. The „*‟ informs the compiler that we want
a pointer variable. i.e. to set aside number of bytes required to store an address in memory. The
Types of Pointer:
There are majorly four types of pointers, they are:
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Null Pointer:
A pointer can also be initialized by assigning a NULL value. It is always a good practice
to assign a NULL value to a pointer variable in case we do not have exact address to be assigned.
This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:
#include <stdio.h>
int main ()
{
return 0;
}
When the above code is compiled and executed, it produces the following result:
Void Pointer:
When a pointer is declared with a void keyword, then it is called a void pointer. To print the
value of this pointer, you need to typecast it.
Syntax:
void *var;
Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Wild Pointer:
A wild pointer is only declared but not assigned an address of any variable. They are very tricky,
and they may cause segmentation errors.
Example:
#include<stdio.h>
When the above code is compiled and executed, it produces the following result:
Dangling Pointer
Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this
memory, then this p is called a dangling pointer.
You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Output:
Value at p1 and p2 are: 50 50
Address pointed by p1 and p2 are: 0052FAD0 0052FAD0
After two assignment statements: p1=&var and p1=p1, p1 and p2 both point to variable
var. Thus, both p1and p2 refer to the same object. It is important to note that the addresses are
displayed by using the %p printf( ) format specifier, which causes printf( ) to display an address
in the format used by the host computer.
Pointer Conversions
It is also possible to assign a pointer of one type to a pointer of another type. This is
achieved using pointer conversion. There are two general types of conversion:
One which involves void * pointer and
Which do not involves void * pointers.
In C, it is allowed to assign a void * pointer to any other type of pointer. It is also allowed to
assign any other type of pointer to a void * pointer. A void * pointer is called a generic pointer.
Usually, the void * type is used to specify a pointer whose base type is unknown.
Except for void * , all other pointer conversions must be performed by using an explicit
cast. However, the conversion of one type of pointer into another type may create undefined
behavior. This illustrated in the following example:
/* pointer conversion*/
#include<stdio.h>
main( )
{
double x=50.6, y;
int *p;
p=(int *) &x; /* p (which is an integer pointer) points to double */
y=*p; /* wrong attempt to assign y the value of x through p */
Address Arithmetic:
Let us consider why we need to identify the type of variable that a pointer points to, as in:
int *ptr;
One reason for doing this is so that later, once prt points to something, if we write:
*prt=2;
Now 2 is assigned to the address location which is pointed by pointer ptr.
The compiler will know how many bytes to copy into that memory location pointed to by
ptr. If ptr was declared as pointing to an integer, 4 bytes would be copied. Similarly for floats
and doubles the appropriate number will be copied. But defining the type that the pointer points
to allow a number of other interesting ways a compiler can interpret code. For example, consider
a block in memory consisting of ten integers in a row. That is, 40 bytes of memory are set aside
to hold 10 integers.
Now let us say we point our integer pointer, ptr at the first of these integers. Let us
assume that integer is located at memory location 1000 (decimal). What happens when we write
ptr+1;
Because the compiler knows this is a pointer (i.e. its value is an address) and that it points to an
integer (its current address, 1000, is the address of an integer) it adds 4 to ptr instead of 1, so the
pointer “points to” the next integer, at memory location 1004. Similarly, if the ptr was declared
as a pointer to a short, it would add 2 to it instead of 1. The same goes for other data types such
as float, double or even user defined data types such as structures. This is obviously not the same
kind of addition that we normally thing of. In C, it is referred to as addition using pointer
arithmetic.
Similarly, since ++ptr and ptr++ are both equivalent to ptr+1, incrementing a pointer using the
unary ++ operator either pre or post, increments the address it stores by the amount sizeof(type)
where type is the type of object pointed to. (i.e. 4 for an integer).
Example:
/* simple program illustrating pointer arithmetic */
#include<stdio.h>
main( )
{
int *p,num;
p=#
*p=100;
printf(“%d\n”,num);
(*p)++;
printf(“%d\n”,num);
Single indirection
Pointer 1 Pointer 2 Variable
Multiple indirection
Pointer to pointer declaration:
A pointer to pointer variable is declared by placing an additional asterisk in front of the
variable name as shown below:
float **amount;
Here, amount is a pointer to pointer of type float.
It is important to note that amount is not a pointer to a floating-point number but rather a
pointer to a float pointer.
One of the best things about pointers is that they allow functions to alter variables outside of
their own scope. By passing a pointer to a function you can allow that function to read and
write to the data stored in that variable. Say we want to write a function that swaps the values of
two variables. Without pointers this would be practically impossible, here's how we do it with
pointers:
#include<stdio.h>
void swap(int *,int *);
main()
{
int a,b;
printf("enter two numbers");
scanf("%d%d",&a,&b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
As we can see, the function declaration of swap( ) tells compiler to expect two pointers
(address of variables). Also, the address-of operator (&) is used to pass the address of the two
variables rather than their values. swap( ) then reads address.
Review Questions