Unit 4 PDF
Unit 4 PDF
Strings in C
In C programming language, there are two methods to create strings and they are
as follows...
Using one dimensional array of character datatype ( static memory allocation )
Using a pointer array of character datatype ( dynamic memory allocation )
Creating string in C programming language
In C, strings are created as a one-dimensional array of character datatype. We can
use both static and dynamic memory allocation. When we create a string, the size
of the array must be one more than the actual number of characters to be stored.
That extra memory block is used to store string termination character NULL (\0).
The following declaration creates a string variable of a specific size at the time of
program execution.
char *str = (char *) malloc(15) ;
Assigning string value in C programming language
The strlen() function returns the length of the given string. It doesn't
count null character '\0'.
#include<stdio.h>
#include<string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is:%d",strlen(ch));
return 0;
}
Output:
Length of string is: 10
Example: C strlen() function
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
// using the %zu format specifier to print size_t
printf("Length of string a = %zu \n",strlen(a));
printf("Length of string b = %zu \n",strlen(b));
return 0;
}
Output
Length of string a = 7
Length of string b = 7
Note that the strlen() function doesn't count the null character \0 while
calculating the length.
C Copy String: strcpy()
#include<stdio.h>
#include<string.h>
int main()
{
char ch[20]={'j','a','v','a','t','p','o','i','n','t','\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Valueof second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint
The strcpy() function is defined in the string.h header file.
Example: C strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str1);//
puts(str2); // C programming
return 0;
}
Output
C programming
C programming
Note: When you use strcpy(), the size of the destination string should be large
enough to store the copied string. Otherwise, it may result in undefined
behavior.
C String Concatenation: strcat()
#include<stdio.h>
#include<string.h>
int main()
{
char ch[10]={'h','e','l','l','o','\0'};
char ch2[10]={'h','a','i','\0'};
strcat(ch,ch2);
printf("Value of first string is:%s",ch);
return 0;
}
Output:
Value of first string is: hellohai
The strcat() function concatenates the destination string and the source string, and
the result is stored in the destination string.
The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.
Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include<string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: javatpoint String is: javatpoint Reverse String is: tnioptavaj
C String Lowercase: strlwr()
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//readsstringfromconsole
printf("String is: %s",str);
printf("\nLower String is:%s",strlwr(str));
return 0;
}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
C String Uppercase: strupr()
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: javatpoint String is: javatpoint Upper String is: JAVATPOINT
C strcmp() Prototype
If the first character of two strings is equal, the next character of two strings are compared.
This continues until the corresponding characters of two strings are different or a null
character '\0' is reached.
It is defined in the string.h header file.
Example: C strcmp() function
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Output
strcmp(str1, str2) = 32
strcmp(str1, str3) = 0
The first unmatched character between string str1 and str2 is third character. The
ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when
strings str1 and str2 are compared, the return value is 32.
When strings str1 and str3 are compared, the result is 0 because both strings are
identical.
C strncmp() Function with example
In the last tutorial we discussed strcmp() function which is used for comparing
two strings. In this guide, we will discuss strncmp() function which is same as
strcmp(), except that strncmp() comparison is limited to the number of characters
specified during the function call.
For example strncmp(str1, str2, 4) would compare only the first four characters of
strings str1 and str2.
This function compares only the first n (specified number of) characters
of strings and returns following value based on the comparison.
#include<stdio.h>
#include<string.h>
void main()
{
charstr[10];
int c=0,i;
printf("ENTER THE STRING\n");
gets(str);
for(i=0;str[i]!='\0';i++)
c++;
printf("LENGTH OF THE STRING IS=%d\n",c);
}
//c program to copy from one string to another without strcpy()
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int i;
printf("ENTER THE STRING\n");
gets(s1);//s1=programming\0 s1[0]=p s2[0]
for(i=0;s1[i]!='\0';i++)
s2[i]=s1[i];
s2[i]='\0';
puts(s2);
}
//wcp to compare two strings without using strcmp()
#include<stdio.h>
#include<string.h>
void main()
{
char s1[100],s2[100];
int l1,l2,flag=0;
printf("ENTER THE STRING1\n");
gets(s1);//HELLO\0
printf("ENTER THE STRING2\n");
gets(s2);//HELLO\0
l1=strlen(s1);//l1=5
l2=strlen(s2);//l2=5
for(i=0;i<l1||i<l2;i++)//i=2 2<5||2<5
{
if(s2[i]!=s1[i])//s2[2]!=s1[2]
{
flag=1;
break;
}
}
if(flag==0)
printf("BOTH STRINGS ARE EQUAL\n");
else
printf("BOTH STRINGS ARE NOT EQUAL\n");
}
//c program to concatenate two strings without using strcat()
void main()
{
char a[100],b[100];
int l1,l2;
printf("ENTER STRING1\n");
gets(a);//helloworld
printf("ENTER STRING2\n");
gets(b);//world
l1=strlen(a);//l1=5
l2=strlen(b);//l2=5
for(i=0;i<l2;i++)//i=1 1<5
a[l1++]=b[i];
a[l1]='\0';
printf("%s\n",a);
}
Write a C Program to check whether given string is palindrome or not.
Pointers in C
In the c programming language, we use normal variables to store user
data values. When we declare a variable, the compiler allocates required
memory with the specified name. In the c programming language, every
variable has a name, datatype, value, storage class, and address.
Example Code
printf("Address : %u", &marks) ;
Example Code
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer
variable that can be used to store any integer variable address.
Assigning Address to Pointer
To assign address to a pointer variable we use assignment operator with the
following syntax...
pointerVariableName = & variableName ;
Example Code
#include<stdio.h>
void main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Value of variable a = %d\n", a) ;
printf("Address of variable a = %d\n", ptr) ;
}
A=10
Ptr=3435445
#include<stdio.h>
void main()
{
int a = 10, *ptr ;
int b=70, *s;
s=&b;
ptr = &a ;
printf("Value of variable a = %d\n", a) ;
printf("Address of variable a = %d\n", ptr) ;
printf("value of b=%d\n",b);
printf("address of variable b=%d",s);
}
Example Program
#include<stdio.h>
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr++ ; // intPtr = 1000 + 2
floatPtr++ ; // floatPtr = 2000 + 4
doublePtr++ ; // doublePtr = 3000 + 6
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
}
The decrement operation on pointer variable is calculated as follows...
AddressAtPointer - NumberOfBytesRequiresByDatatype
Example Program
#include<stdio.h>
void main() {
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
intPtr-- ; // intPtr = 1000 - 2
floatPtr-- ; // floatPtr = 2000 - 4
doublePtr-- ; // doublePtr = 3000 – 6
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
}
Comparison of Pointers
The comparison operation is perform between the
pointers of same datatype only. In c programming
language, we can use all comparison operators
(relational operators) with pointers.
Example Program
int **ptr ;
Here, ptr is an integer pointer variable that stores the address of another integer
pointer variable but does not stores the normal integer variable address.
MOST IMPORTANT POINTS TO BE REMEMBERED
#include<stdio.h>
int main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;
ptr1 = &a ;
ptr2 = &ptr1 ;
ptr3 = &ptr2 ;
printf("\nAddress of normal variable 'a' = %u\n", ptr1) ;
printf("Address of pointer variable '*ptr1' = %u\n", ptr2) ;
printf("Address of pointer-to-pointer '**ptr2' = %u\n", ptr3) ;
}
Pointers to void in C
In the c programming language, pointer to void is the concept of
defining a pointer variable that is independent of data type. In C
programming language, a void pointer is a pointer variable used to store
the address of a variable of any datatype. That means single void pointer
can be used to store the address of integer variable, float variable,
character variable, double variable or any structure variable.
We use the keyword "void" to create void pointer.
Example Code
void *ptr ;
Here, "ptr" is a void pointer variable which is used to store the address
of any datatype variable.
MOST IMPORTANT POINTS TO BE REMEMBERED
void pointer stores the address of any datatype variable.
Example Program
#include<stdio.h>
int main()
{
int a ;
float b ;
char c ;
void *ptr ;
ptr = &a ;
printf(“Address of integer variable ‘a’ = %u\n”, ptr) ;
ptr = &b ;
printf(“Address of float variable ‘b' = %u\n”, ptr) ;
ptr = &c ;
printf(“Address of character variable ‘c’ = %u\n”, ptr) ;
}
Pointers to Arrays in C
In the c programming language, when we declare an array the compiler
allocate the required amount of memory and also creates a constant
pointer with array name and stores the base address of that pointer in it.
The address of the first element of an array is called as base address of
that array.
The array name itself acts as a pointer to the first element of that array.
Example Code
int marks[6] ;
#include<stdio.h>
int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;
ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
}
MOST IMPORTANT POINTS TO BE REMEMBERED
An array name is a constant pointer.
We can use the array name to access the address and value of all the elements of
that array.
Since array name is a constant pointer we can't modify its value.
Example Code
ptr = marks + 2 ;
Example Code
printf("Address of 'marks[4]' = %u", marks+4) ;
Example Code
marks++ ;
The above statement generates compilation error because the array name acts
as a constant pointer. So we can't change its value.
In the above example program, the array name marks can be used as follows...
marks is same as &marks[0]
marks + 1 is same as &marks[1]
marks + 2 is same as &marks[2]
marks + 3 is same as &marks[3]
marks + 4 is same as &marks[4]
marks + 5 is same as &marks[5]
*marks is same as marks[0]
*(marks + 1) is same as marks[1]
*(marks + 2) is same as marks[2]
*(marks + 3) is same as marks[3]
Pointers to Multi Dimensional Array
In case of multi dimensional array also the array name acts
as a constant pointer to the base address of that array. For
example, we declare an array as follows...
Example Code
int marks[3][3] ;
De-allocation function
4. free()
1. malloc(): a block of memory is allocated
char *a;
a=char *malloc(sizeof(char));
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a;
a=(int *)malloc(sizeof(int));
scanf("%d",a);
printf("%d\n",*a);
free(a);
printf("%d",*a);
}
/*read and print 1d array using malloc function*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a;
int n,i;
printf("enter no of blocks");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",(a+i));
}
for(i=0;i<n;i++)
{
printf("%d\n",*(a+i));
}
}
/*1d array reading and printing reverse order using malloc*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a;
int n,i;
printf("enter no of blocks");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",(a+i));
}
for(i=n-1;i>=0;i--)
{
printf("%d\n",*(a+i));
}
}
/*program to swap two numbers by allocating memory by call by reference
method*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,*b;
a=(int *)malloc(sizeof(int));
b=(int *)malloc(sizeof(int));
printf("enter a,b values");
scanf("%d%d",a,b);
swap(a,b);
printf("After swaping a=%d,b=%d",*a,*b);
}
int swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
2. calloc():contigious memory allocation function,mainly it used
with arrays
Syntax: (void*)calloc(n,sizeof(datatype));
int *a;
(int *)calloc(10,sizeof(int));
->>returntype is void
🡪null value
/*read and print an array using calloc() function*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a;
intn,i;
printf("enter no of blocks");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",(a+i));
}
for(i=0;i<n;i++)
{
printf("%d\n",*(a+i));
}
}
3. realloc():reallocation of memory
a=(int *)calloc(n,sizeof(int)); 0 1 2 3 4
11 12 12 13 14
a=(int *)realloc(a,2*sizeof(int)); 0 1 2 3 4 5 6
11 12 12 13 14 56 78
/*program for allocation and reallocation*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a;
int n,i,n1;
printf("enter no of blocks");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",(a+i));
}
for(i=0;i<n;i++)
{
printf("%d\n",*(a+i));
}
printf("enter extra size");
scanf("%d",&n1);
a=(int *)realloc(a,n1*sizeof(int));
for(i=0;i<n1;i++)
scanf("%d",(a+i));
for(i=0;i<n1;i++)
printf("%d",*(a+i));
}
Dynamic Memory Allocation in C
In C programming language, when we declare variables memory is allocated in space called
stack. The memory allocated in the stack is fixed at the time of compilation and remains until
the end of the program execution. When we create an array, we must specify the size at the
time of the declaration itself and it can not be changed during the program execution. This is
a major problem when we do not know the number of values to be stored in an array.
To solve this we use the concept of Dynamic Memory Allocation. The dynamic memory
allocation allocates memory from heap storage.
Syntax
void* malloc(size_in_bytes)
Example
#include<stdio.h>
int main () {
char *title;
title = (char *) malloc(15);
strcpy(title, "c programming");
printf("Before modification : String = %s, Address = %u\n", title, title);
title = (char*) realloc(title, 30);
strcpy(title,"C Programming Language");
printf("After modification : String = %s, Address = %u\n", title, title);
free(title);
}