100% found this document useful (1 vote)
200 views69 pages

Unit 4 PDF

The document discusses strings in C programming language. It begins by defining a string as a set of characters enclosed in double quotes. Strings in C are implemented as one-dimensional character arrays that are terminated with a null character. The document then discusses different ways to declare and initialize strings in C, such as static and dynamic memory allocation. It also covers functions for manipulating strings like strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().

Uploaded by

Uday Kumar M
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
100% found this document useful (1 vote)
200 views69 pages

Unit 4 PDF

The document discusses strings in C programming language. It begins by defining a string as a set of characters enclosed in double quotes. Strings in C are implemented as one-dimensional character arrays that are terminated with a null character. The document then discusses different ways to declare and initialize strings in C, such as static and dynamic memory allocation. It also covers functions for manipulating strings like strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().

Uploaded by

Uday Kumar M
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/ 69

UNIT-IV

Strings in C

String is a set of characters that are enclosed in double quotes. In the C


programming language, strings are created using one dimension array of character
datatype. Every string in C programming language is enclosed within double
quotes and it is terminated with NULL (\0) character. Whenever c compiler
encounters a string value it automatically appends a NULL character (\0) at the
end.

The formal definition of string is as follows...


String is a set of characters enclosed in double quotation marks. In C
programming, the string is a character array of single dimension.

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 stores a string of size 5 characters.


char str[6] ;

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

String value is assigned using the following two methods...


At the time of declaration (initialization)
After declaraation

Examples of assigning string value


#include<stdio.h>
int main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name2[6] = {'s','m','a','r','t'};
printf("%s\n",str1);
printf("%s\n",str2);
printf("%s\n",name2);
return 0;
}
Reading string value from user in C programming language
We can read a string value from the user during the program execution.

We use the following two methods...


Using scanf() method - reads single word
Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent string in
scanf() and printf() methods.
Examples of reading string value using scanf() method
#include<stdio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to smart class !!", name);
return 0;
}
o/p:Please enter your name:
Hello!spandana welcome to smart class!!
When we want to read multiple words or a line of text, we use a pre-defined
method gets().
The gets() method terminates the reading of text with Enter character.

Examples of reading string value using gets() method


#include<stdio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to smart class !!", name);
return 0;
}
o/p:please enter your name:ss
Hello! ss welcome to smart class!!
C Programming language provides a set of pre-definied functions
called String Handling Functions to work with string values. All the
string handling functions are defined in a header file called string.h.

String Handling Functions in C


C programming language provides a set of pre-defined functions
called string handling functions to work with string values. The string
handling functions are defined in a header file called string.h.
Whenever we want to use any string handling function we must include
the header file called string.h.
C String Length:
strlen() function

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()

The strcpy(destination, source) function copies the source string in


destination.

#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()

The strcat(first_string, second_string) function concatenates two strings


and result is returned to first_string.

#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.

Example: C strcat() function


#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "This is ", str2[] = "programiz.com";
// concatenates str1 and str2
// the resultant string is stored in str1.
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
}
Output
This is programiz.com
programiz.com
Note:
When we use strcat(), the size of the destination string should be large enough to
store the resultant string. If not, we will get the segmentation fault error.
C Compare String: strcmp()

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()

The strlwr(string) function returns string characters in lowercase.


Let's see a simple example of strlwr() function.

#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()

The strupr(string) function returns string characters in uppercase.

Let's see a simple example of strupr() 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("\nUpper String is: %s",strupr(str));
return 0;
}

Output:
Enter string: javatpoint String is: javatpoint Upper String is: JAVATPOINT
C strcmp() Prototype

int strcmp (const char* str1, const char* str2);

The strcmp() function takes two strings and returns an integer.


The strcmp() compares two strings character by character.

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.

C strncmp() function declaration


int strncmp(const char *str1, const char *str2, size_t n)
str1 – First String
str2 – Second String
n – number of characters that needs to be compared.
Return value of strncmp()

This function compares only the first n (specified number of) characters
of strings and returns following value based on the comparison.

0, if both the strings str1 and str2 are equal


>0, if the ASCII value of first unmatched character of str1 is greater
than str2
<0, if the ASCII value of first unmatched character of str1 is less than
str2
Example 1: strncmp() function in C
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20]; char str2[20]; int result;
//Assigning the value to the string str1
strcpy(str1, "hello");
//Assigning the value to the string str2
strcpy(str2, "helLO WORLD");
//This will compare the first 3 characters
result = strncmp(str1, str2, 3);
if(result > 0)
{
printf("ASCII value of first unmatched character of str1 is greater than str2");
}
else if(result < 0)
{
printf("ASCII value of first unmatched character of str1 is less than str2");
}
else
{
printf("Both the strings str1 and str2 are equal");
}
return 0;
}
Output:
Both the strings str1 and str2 are equal
//FIND THE LENGTH OF THE STRING WITHOUT USING STRLEN()

#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.

We use a special type of variable called a pointer to store the address of


another variable with the same datatype.

A pointer is defined as follows...


Pointer is a special type of variable used to store the memory
location address of a variable.

In the c programming language, we can create pointer variables of any


datatype. Every pointer stores the address the variable with same
datatype only. That means integer pointer is used store the address of
integer variable only.
Accessing the Address of Variables

In c programming language, we use the reference operator


"&" to access the address of variable. For example, to
access the address of a variable "marks" we
use "&marks". We use the following printf statement to
display memory location address of variable "marks"...

Example Code
printf("Address : %u", &marks) ;

In the above example statement %u is used to display


address of marks variable. Address of any memory location
is unsigned integer value.
Declaring Pointers (Creating Pointers)
In c programming language, declaration of pointer variable is similar to
the creation of normal variable but the name is prefixed with * symbol.

We use the following syntax to declare a pointer variable...


datatype *pointerName ;

A variable declaration prefixed with * symbol becomes a pointer


variable.

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 ;

For example, consider the following variables declaration...


Example Program | Test whether given number is divisible by 5.
int a, *ptr ;

In the above declaration, variable "a" is a normal integer variable and


variable "ptr" is an integer pointer variable. If we want to assign the address of
variable "a" to pointer variable "ptr"
we use the following statement...
Example Code
ptr = &a ;

In the above statement, the address of variable "a" is assigned to pointer


variable "prt". Here we say that pointer variable ptr is pointing to variable a.
Accessing Variable Value Using Pointer
Pointer variables are used to store the address of other variables. We can use this
address to access the value of the variable through its pointer. We use the
symbol "*" infront of pointer variable name to access the value of variable to
which the pointer is pointing.

We use the following general syntax...


*pointerVariableName

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);
}

In the above example program, variable a is a normal variable and


variable ptr is a pointer variable. Address of variable a is stored in pointer
variable ptr. Here ptr is used to access the address of variable a and *ptr is
used to access the value of variable a.
Memory Allocation of Pointer Variables

Every pointer variable is used to store the address of


another variable. In computer memory address of any
memory location is an unsigned integer value.

In c programming language, unsigned integer requires 2


bytes of memory. So, irrespective of pointer datatype every
pointer variable is allocated with 2 bytes of memory.
Pointers Arithmetic Operations in C
Pointer variables are used to store the address of variables. Address of
any variable is an unsigned integer value i.e., it is a numerical value. So
we can perform arithmetic operations on pointer values.

But when we perform arithmetic operations on pointer variable, the


result depends on the amount of memory required by the variable to
which the pointer is pointing.

In the c programming language, we can perform the following


arithmetic operations on pointers...
Addition
Subtraction
Increment
Decrement
Comparison
Addition Operation on Pointer
In the c programming language, the addition operation on pointer variables is
calculated using the following formula...
AddressAtPointer + ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
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 + 3 ; // intPtr = 1000 + ( 3 * 2 )
floatPtr = floatPtr + 2 ; // floatPtr = 2000 + ( 2 * 4 )
doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 6 )
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
}
Subtraction Operation on Pointer
In the c programming language, the subtraction operation on pointer variables is
calculated using the following formula...
AddressAtPointer - ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
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 - 3 ; // intPtr = 1000 - ( 3 * 2 )
floatPtr = floatPtr - 2 ; // floatPtr = 2000 - ( 2 * 4 )
doublePtr = doublePtr - 5 ; // doublePtr = 3000 - ( 5 * 6 )
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
}
Increment & Decrement Operation on Pointer
The increment 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) ;
}
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.

We can't perform multiplication and division


operations on pointers.
Pointers to Pointers in C
In the c programming language, we have pointers to store the address of
variables of any datatype.
A pointer variable can store the address of a normal variable. C programming
language also provides a pointer variable to store the address of another pointer
variable.
This type of pointer variable is called a pointer to pointer variable. Sometimes
we also call it a double pointer.

We use the following syntax for creating pointer to pointer…


datatype **pointerName ;

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

To store the address of normal variable we use single


pointer variable
To store the address of single pointer variable we use
double pointer variable
To store the address of double pointer variable we use
triple pointer variable
Similarly the same for remaining pointer variables
also…
Example Program

#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.

We use the following syntax for creating a pointer to void…


void *pointerName ;

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.

Consider the following example of array declaration...

Example Code
int marks[6] ;

For the above declaration, the compiler allocates 12 bytes of memory


and the address of first memory location (i.e., marks[0]) is stored in a
constant pointer called marks. That means in the above
example, marks is a pointer to marks[0].
Example Program

#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 ;

Here, the pointer variable "ptr" is assigned with address


of "marks[2]" element.

Example Code
printf("Address of 'marks[4]' = %u", marks+4) ;

The above printf statement displays the address of


element "marks[4]".
Example Code
printf("Value of 'marks[0]' = %d", *marks) ;
printf("Value of 'marks[3]' = %d", *(marks+3)) ;
In the above two statements,
first printf statement prints the value 89 (i.e., value of marks[0]) and
the second printf statement prints the value 72 (i.e., value of marks[3]).

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] ;

In the above example declaration, the array


name marks acts as constant pointer to the base address
(address of marks[0][0]) of that array.

In the above example of two dimensional array, the


element marks[1][2] is accessed as *(*(marks + 1) + 2).
Pointers for Functions in C

In the c programming language, there are two ways to pass parameters


to functions. They are as follows...
1)Call by Value
2)Call By Reference

We use pointer variables as formal parameters in call by


reference parameter passing method.

In case of call by reference parameter passing method, the address of


actual parameters is passed as arguments from the calling function to
the called function. To recieve this address, we use pointer variables as
formal parameters.
Consider the following program for swapping two variable values...
Example - Swapping of two variable values using Call by Reference
#include<stdio.h>
void swap(int *, int *) ;
void main()
{
int a = 10, b = 20 ;
printf(“Before swap : a = %d and b = %d\n", a, b) ;
swap(&a, &b) ;
printf(“After swap : a = %d and b = %d\n", a, b) ;
}
void swap(int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
} In the above example program, we are passing the addresses of variables a and b and
these are recieved by the pointer variables x and y. In the called function swap we use the
pointer variables x and y to swap the values of variables a and b.
•Memory allocation functions

int a; a=4bytes of memory allocated


int a[10] a=40 bytes of memory allocated

Two types of memory allocations


1. static memory allocation
2. dynamic memory allocation

Static allocation means allocating memory at compile time


int a;
int a[40]={1,2,3};

Dynamic allocation means allocating memory at run time


1. malloc()
2. calloc()
3. realloc()

De-allocation function
4. free()
1. malloc(): a block of memory is allocated

Syntax: (void *)malloc(sizeof(datatype));


Eg: int *a;
a=(int *)malloc(sizeof(int));

char *a;
a=char *malloc(sizeof(char));

🡪the return type is void


🡪the default value stored is garbage
‘N’ blocks of memory allocate

Syntax: (void *)malloc(n*sizeof(datatype));


/*program to allocate a block of memory using malloc function*/

#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

Syntax: (void *)realloc(void * oldpointer,newsize);


Eg:int *a;
N=5;

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.

Dynamic memory allocation is defined as follow...


Allocation of memory during the program execution is called dynamic memory
allocation.
or
Dynamic memory allocation is the process of allocating the memory manually at the
time of program execution.

We use pre-defined or standard library functions to allocate memory dynamically. There


are FOUR standard library functions that are defined in the header file known as "stdlib.h".
They are as follows...
malloc()
calloc()
realloc()
free()
malloc()
malloc() is the standard library function used to allocate a memory block of specified number
of bytes and returns void pointer. The void pointer can be casted to any datatype. If malloc()
function unable to allocate memory due to any reason it returns NULL pointer.

Syntax
void* malloc(size_in_bytes)

Example

Example Program for malloc().


#include<stdio.h>
int main ()
{
char *title;
title = (char *) malloc(15);
strcpy(title, "c programming");
printf("String = %s, Address = %u\n", title, title);
}
calloc()
calloc() is the standard library function used to allocate multiple memory blocks of the specified
number of bytes and initializes them to ZERO. calloc() function returns void pointer. If calloc()
function unable to allocate memory due to any reason it returns a NULL pointer. Generally,
calloc() is used to allocate memory for array and structure. calloc() function takes two arguments
and they are 1. The number of blocks to be allocated, 2. Size of each block in bytes
Syntax
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example
Example Program for calloc().
#include<stdio.h>
void main () {
int i, n;
int *ptr;
printf("Number of blocks to be created:");
scanf("%d",&n);
ptr = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&ptr[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
{
printf("%d ",ptr[i]);
}
realloc()
realloc() is the standard library function used to modify the size of memory blocks that were
previously allocated using malloc() or calloc(). realloc() function returns void pointer. If
calloc() function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example
Example Program for realloc().
#include<stdio.h>
void 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()
free() is the standard library function used to deallocate memory block that was previously
allocated using malloc() or calloc(). free() function returns void pointer. When free()
function is used with memory allocated that was created using calloc(), all the blocks are get
deallocated.
Syntax
void free(*pointer)
Example
Example Program for free().

#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);
}

You might also like