0% found this document useful (0 votes)
18 views83 pages

Pointers 1

The document explains various functions for formatting data in memory, specifically focusing on sprintf() and sscanf(). It also covers pointers in C, including their types, usage, and operations such as pointer arithmetic, function pointers, and pointers to pointers. Additionally, it discusses different pointer types like NULL, void, dangling, and wild pointers, along with examples and practices for better understanding.

Uploaded by

dharmeshbardhan
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)
18 views83 pages

Pointers 1

The document explains various functions for formatting data in memory, specifically focusing on sprintf() and sscanf(). It also covers pointers in C, including their types, usage, and operations such as pointer arithmetic, function pointers, and pointers to pointers. Additionally, it discusses different pointer types like NULL, void, dangling, and wild pointers, along with examples and practices for better understanding.

Uploaded by

dharmeshbardhan
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/ 83

Functions for Formatting Data in

Memory
The formatting functions are available as a part
of the standard library. The following functions
are used to format data in memory:

sprintf()
sscanf()

These functions, like printf() or scanf() write


variables to a destination or read data for
variables from a destination.

The difference is that while printf() writes to


the screen, sprintf() writes to a variable in the
memory and stores the data in different
variables specified. These functions are used
for transferring data between variables in a
specific format.
The syntax of the function sprintf()
sprintf(string, format-specification, data, ….);

where:
 string is a pointer to the destination string in memory,
which will contain the formatted data as per the
format-specification.

 format-specification is the specification of how data is


to be formatted.
 data is the list of data to be formatted

For example, after the statement:

sprintf(str, “%02d-%02d-%02d”,28,8,89);

is executed, str will contain:


28-08-89
The function sprintf() is useful for formatting data and
controlling the width of the destination string.
Char str[30]=“28thAugust1989”

sscanf(str, “%2d%2s%s%d”, &day, suffix, mnth, &year);

printf(“The day is %d, suffix is: %s, month is: %s, year is:
%%d\n”, day, suffix, mnth, year);

If the data in str is 28thAugust 1989,

the output will be:

The day is: 28, suffix is :th, month is August, year is :


1989

Practice 5.7
What data is assigned to the variable string by each of
the following?
 sprintf (string, "%04d%3.2f%2s", 21, 4.576, "Hi");
 sprintf (string, "%10s", "ABC");
 sscanf ("0987APZ", "%4d%s", &num, string);
a. “00214.58Hi”
b. “ABC”
c. “APZ”
Pointer in c
A pointer is a variable like any other variable
which contain an address of another variable,
having same data types as pointer type.

you must declare a pointer before using it to


store any variable address. The general form of
a pointer variable declaration is −

type *pointer-name;

Here, type is the pointer's base type; it must be


a valid C data type and pointer-name is the name
of the pointer variable. The asterisk * used to
declare a pointer is the same asterisk used for
multiplication. However, in this statement the
asterisk is being used to designate a variable as
a pointer.
A block of memory is reserved by the compiler
when we declare a variable. To store these
memory addresses, C allows programmers to use
the concept of pointers that can hold the
address of any other data type. Pointers can be
de-referenced using the asterisk * operator to
get the value stored in an address.

Take a look at some of the valid pointer


declarations −

int *iptr; /* pointer to an integer */


double *dptr; /* pointer to a double */
float *fptr; /* pointer to a float */
char *cptr /* pointer to a character */
How to Use Pointers?
There are a few important operations, which we
will do with the help of pointers very
frequently.

(a) We define a pointer variable,


(b) assign the address of a variable to a pointer
(c) finally access the value at the address
available in the pointer variable.

This is done by using unary operator * that


returns the value of the variable located at the
address specified by its operand.
#include<stdio.h>
main()
{
int i=10;
int *ptr;
ptr=&i;
printf("i=%d\n",i);
printf("i=%x\n",ptr);
printf(“i=%d\n”,*ptr);
}
Types of Pointers
NULL Pointer
It is always a good practice to assign a NULL value to a
pointer variable in case you do not have an 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.

#include <stdio.h>

int main () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}
Void Pointer
The void pointer in C is a pointer that is not
associated with any data types. It points to
some data location in the storage. This means
that it points to the address of variables. It is
also called the general purpose pointer.

#include <stdio.h>

int main()
{
int a = 10;
void *ptr = &a; // Void pointer
printf("Value of a: %d\n", *(int*)ptr);
// Typecasting is needed
return 0;
}
Advantages of Void Pointers
Following are the advantages of void pointers

 malloc() and calloc() return void * type and


this allows these functions to be used to
allocate memory of any data type (just
because of void *).

 void pointers in C are used to implement


generic functions in C.
Dangling Pointer
A pointer pointing to memory that has been freed.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr = (int *)malloc(sizeof(int));
*ptr = 42;
free(ptr); // Memory deallocated
// Accessing `ptr` now creates a dangling pointer issue
return 0;
}
Wild Pointer
An uninitialized pointer that can cause unpredictable
behavior.

#include <stdio.h>
int main()
{
int *ptr; // Wild pointer
// Use after initialization to avoid issues
return 0;
}
Function Pointer
A pointer used to store the address of a function.

#include <stdio.h>
void display()
{
printf("Function pointer example.\n");
}
int main()
{
void (*funcPtr)() = display; // Function pointer
funcPtr(); // Call the function
return 0;
}
Pointer to Pointer
Pointer to a pointer is a form of multiple indirection or
a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a
pointer, the first pointer contains the address of the
second pointer, which points to the location that
contains the actual value.

Example :
following is the declaration to declare a pointer to a
pointer of type int −

int **var;
When a target value is indirectly pointed to by a
pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown
below in the example −
Pointer to Pointer

#include <stdio.h>
int main()
{
int a = 10;
int *ptr = &a; // Pointer to int
int **ptr2 = &ptr; // Pointer to pointer
printf("Value of a: %d\n", **ptr2);

return 0;
}
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr,***p3,****p4;
var = 3000;
// take the address of var
ptr = &var;
// take the address of ptr using address of operator &
pptr = &ptr;
p3=&pptr;
p4=&p3;
// take the value using pptr
printf("Value of var :%d\n",var);
printf("Value available at *ptr :%d\n",*ptr);
printf("Value available at **pptr :%d\n",**pptr);
printf("Value available at ***p3 :%d\n",***p3);
printf("Value available at ****p4 :%d\n",****p4);
return 0;
}
#include<stdio.h>
int main()
{
int x[5]={1,2,9,8,5};
int *p;
p=x; //p=&x[0];

printf("%d\t%d\t%d\t%d\t%d\n",p[0],p[1],p[2],p[3],p[4]);

printf("%d\t%d\t%d\t%d\t%d\n",&p[0],&p[1],&p[2],&p[3],
&p[4]);
printf("%d\t%d\n",x[0],p);
printf("%d\t%d\n",*p,p);
printf("%d\t%d\n",*p++,p);
printf("%d\t%d\n",*(++p),p);
printf("%d\t%d\n",*(p+2),p);
p=&x[3];
printf("%d\t%d\n",*p,p);
printf("%d\t%d\n",*(p-2),p);
}
Constant Pointer
A pointer that cannot change the memory location it
points to.

#include <stdio.h>
int main()
{
int a = 10, b = 20;
int *const ptr = &a; // Constant pointer
*ptr = 30; // Allowed: changing the value of 'a'
// ptr = &b; // Error: cannot change the address
return 0;
}
Usage of Pointers
Pointer arithmetic
There are four arithmetic operators that can be used
in pointers: ++, --, +, -

Array of pointers
You can define arrays to hold a number of pointers.

Pointer to pointer
C allows you to have pointer on a pointer and so on.

Passing pointers to functions in C


Passing an argument by reference or by address enable
the passed argument to be changed in the calling
function by the called function.

Return pointer from functions in C


C allows a function to return a pointer to the local
variable, static variable, and dynamically allocated
memory as well.
Practice (Just a Minute)
1) In the declaration:

float *ptr_to_float;
the pointer variable ptr_to_float can point to a
variable of type .

2) Is the following declaration valid?


*ptr_to_something;

3)State whether True or False: In the


declaration:
int *ptr_to_int; an integer is being declared.

4)Is the declaration:


int some_int, *ptr_to_int;
valid?
Pointer arithmetic
#include<stdio.h>
main()
{
int x,y,z,*ptr;
x=34;
y=67;
z=20;

printf("X=%d, y=%d\n",x,y); //X=34 y=67

ptr=&x;
y=*ptr;

printf("X=%d, y=%d\n",x,y); //x=34 y=34


z=*ptr+1;
printf("z=%d\n",z); //z will be 35
*ptr=0;
printf("X=%d",x); // x will be 0
}
#include<stdio.h>
Int main()
{
int a,b,*p1, *p2;
a=20;
b=40;
p1=&a; p2=&b;
printf(“ a=%d, b=%d”, *p1, *p2);
/*output. a=20, b=40 */

printf(“ a=%d, b=%d”, a, b);


/*output. a=20, b=40 */

*p2=*p1; /*b gets the value stored in a. Assignment 1 */


printf(“a=%d, b=%d”, *p1, *p2);
/*output. a=20, b=20 */

printf(“a=%d, b=%d”, a,b);


/* output: a=20,b=20 */
a=30;
b=50;

p2=p1; /*p2 also points to the variable to which p1


points. Assignment 2 */
printf(“a=%d , b=%d”, *p1, *p2);

/* output: a=30, b=30 because p2 now points to a */

printf(“a=%d ,b=%d”, a , b);

/* output: a=30, b=50 */


/* actual value of b is still 50!! */
/* Note the difference in the preceding two assignments 1
& 2 */
}
Practice
1)The symbol is used to obtain the
address of a variable while the symbol
is used to obtain the value of the
variable to which a pointer is pointing to.

2)With the following declarations:


int x, y, *ptr;
Which of the following are meaningful
assignments?
a. x = y;
b. y=*ptr;
c. x = ptr;
d. x= &ptr;
e. ptr = &x;
f. x = &y;
Practice
Consider the following sequence of statements and
complete the partially-filled table:

int x, y, *ptr1 *ptr2;


x = 65;
y = 89;
ptr1 = &x; /*ptr1 points to x */
ptr2 = &y; /* ptr2 points to y */
x = *ptr1; /* statement A*/
ptr1 = ptr2 ; /* statement B */
x = *ptr1; /* statement C*/

After statement &x x &y y ptr1 ptr2


A 1006 1018
B
C
Practice
What is the output of the following sequence of
statements:

int x, y, temp,*ptr1, *ptr2; /* declare */


x = 23;
y = 37;
ptr1= &x; /* ptrl points to x */
ptr2 = &y; /* ptr2 points to y */
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
printf(“x is %d while y is %d”, x, y);
Pointer Arithmetic
Arithmetic operations of incrementing and
decrementing can be performed on pointers. In
fact, pointer arithmetic is one of the reasons
why it is essential to declare a pointer as
pointing to a certain datatype so that when the
pointer is incremented or decremented, it
moves by the appropriate number of bytes.

Thus, the following statement:

ptr++;
does not necessarily mean that ptr now points
to the next memory location. What memory
location it will point to will depend upon the
datatype to which the pointer points. Consider
the following example:
#include <stdio.h>
char college[]= “CIMAGE COLLEGE”;
main()
{
char *ptr;
ptr=college;
printf(“%s”, college); /* output: CIMAGE COLLEGE*/
printf(“%s”,ptr); /* output: CIMAGE COLLEGE
*/

ptr++;
printf(“%s”,college); /* output: CIMAGE COLLEGE */
printf(“%s",ptr); /* output: IMAGE COLLEGE*/

ptr++;
printf(“%s”,college); /* output; CIMAGE COLLEGE*/
printf(“%s”,ptr); /* output: MAGE COLLEGE*/

/* Note that the incrementing of the pointer ptr does


not in any way affect the pointer college*/
}
Using Pointers to Manipulate Character
Arrays
While discussing arrays and addressing, we
mentioned that the array name contains the
address of the first element of the array.

We also defined a pointer, in an earlier section,


as a variable, which can store the address of
another variable.

The logical conclusion then is that the array


name is actually a pointer which points to
starting element of an array.
One-Dimensional Arrays and Pointers

The array name contains the base address of an


array. Therefore, it is a pointer and hence can be
manipulated using pointers. The following example
manipulates a one-dimensional array by using a
pointer:

#include <stdio.h>
char str[13]={“CIMAGE PATNA”};
char str1[]={“MAGIC”};
main()
{
char *ptr;
printf(“We are playing around with %s", str);
/* Output: We are playing around with CIMAGE PATNA */
ptr=str ; /* ptr now points to whatever str is pointing to */
printf(“We are playing around with %s" ,ptr);
/* Output: We are playing around with CIMAGE PATNA */
}
Although the preceding example gives the
impression that the two pointers are equal,
there is a very subtle difference between str
and ptr.
Both, ptr and str are pointers to char datatype.
However, str is a pointer, which is static.

Its value is fixed as the address of the first


element of the contiguous block of 13 bytes,
which are allocated when the array is declared,
its value, therefore, cannot be changed.

On the other hand, ptr is a pointer, which is


dynamic. It can potentially contain the address
of any area in memory. After the following
assignment:
ptr = str;
ptr contains the address of the first element of
the array str. Its value can be changed by a
simple reassignment:

ptr=str1;

A pointer can also be used to initialize a string


within a function, as shown in the following code
snippet:

char *movie = “Jurassic Park”;


printf(“Oscar Award for Best Sound Effects:
%s”, movie);

/*Output: Oscar Award for Best Sound


Effects: Jurassic Park*/
Practice
1. Given the declaration:
char some_string [10];
some_string points to .

2. State whether True or False:


In the declaration:
char *err_msg = “Some error message”;

the pointer err_msg contains a valid address.

3. State whether True or False:


The declaration:

char *err_msg = “Some error message”;


Two-Dimensional Arrays and Pointers

Extending the logic of declaring one-dimensional


character arrays, we can also declare two-d
character arrays. Consider the following
declaration:

char *things[6];

/* declaring an array of 6 pointers to char */

Individual strings can be initialized by separate


assignment statements because each element of
this array is a pointer. Consider the following
initializations:
things[0]=”Raindrops on roses”;
things[1]=”And Whiskers on kettles”;
things[2]=”Bright copper kettles”;
things[3]=”And warm woolen mittens”;
things[4]=”Brown paper packages tied up with strings”;
things[5]=”These are a few of my favorite things”;

The third line of the song can be printed by the


following statement:

printf(“%s”, things[2]);

/*Output: Bright copper kettles */


Excercise
Given the following error messages:

All's well,
File not found
No read permission for file
Insufficient memory
No write permission for file

Write a program to print all the error messages


on screen, using pointers to array.
#define Directive (macro definition)
 In the C Programming Language, the #define
directive allows the definition of macros within your
source code. These macro definitions allow constant
values to be declared for use throughout your code.

 Macro definitions are not variables and cannot be


changed by your program code like variables. You
generally use this syntax when creating constants
that represent numbers, strings or expressions.

Syntax
The syntax for creating a constant using #define in
the C language is:

#define CNAME value

OR

#define CNAME (expression)


CNAME
The name of the constant. Most C programmers
define their constant names in uppercase, but it is not
a requirement of the C Language.
value
The value of the constant.
expression
Expression whose value is assigned to the constant.
The expression must be enclosed in parentheses if it
contains operators.

Note
Do NOT put a semicolon character at the end of
#define statements. This is a common mistake.
Example
Let's look at how to use #define directives with
numbers, strings, and expressions.

Number
The following is an example of how you use the #define
directive to define a numeric constant:

#define AGE 10
In this example, the constant named AGE would contain
the value of 10.

String
You can use the #define directive to define a string
constant.

For example:

#define NAME “CIMGAE COLLEGE"


In this example, the constant called NAME would contain
the value of " CIMGAE COLLEGE ".
Expression
You can use the #define directive to define a constant using
an expression.

For example:

#define AGE (28 / 2)


In this example, the constant named AGE would also contain
the value of 14.

#include <stdio.h>

#define NAME “CIMAGE "


#define AGE 14
#define MIN(a,b) ((a)<(b)?(a):(b))

int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
return 0;
}
# include<stdio.h>
# define ERRORS 5

char *err_msg[]= {
/*Note the missing index*/
“All's well”,
“File not found”,
“No read permission for file”,
“Insufficient memory”,
“No write permission for file”
};

main()
{
int err_no;
for ( err_no = 0; err_no < ERRORS; err_no++ )
{
printf (“\nError message %d is : %s\n”, err_no + 1,
err_msg[err_no]);
}
}
Now, let us complicate things a little further
and apply pointer arithmetic to two-d arrays.
Consider the following declaration:

int num[3][4]=
{
{3, 6, 9, 12},
{15, 25, 30, 35},
{66, 77, 88, 99}
};
Pointer expression Variable Value

*(*num) num[0][0] 3
*(*num+1) num[0][1] 6
*(*(num+1)) num[1][0] 15
*(*(num+1)+ 1) num[1][1] 25
*(*(num+1)+ 1)+1 num[1][1] + 1 26
The following code snippet would help you to understand
the use of the indirection symbol to access various
elements:

*num is equal to num[0] because num[0] points to num[0][0].


*(*num) will give the value 3.
*num is equal to num[0].
num[0] contains the address of num[0][0].
*num + 1 would be equal to num[0][1].
*(*num + 1) will give the value 6. num points to num[0].
num + 1 would point to num[1].
*(num + 1) points to num[1][0].
*(*(num + 1)) gives the value 15. num points to num[0].
num + 1 would point to num[1].
*(num + 1) points to num[1][0].
*(num + 1) + 1 points to num[1][1].
*(*(num + 1) + 1) will give 25.
*(*(num + 1) + 1) + 1 will give 26.
String-Handling Functions Using
Pointers
/* function to calculate length of a string*/
#include <stdio.h>
main()
{
char *ptr, str[20];
int size=0;
printf(“\nEnter string:”);
gets(str);
fflush(stdin);

for(ptr=str ; *ptr != '\0'; ptr++)


{
size++;
}

printf(“String length is %d”, size);


}
function to check for a palindrome
/*function to check for a palindrome */
#include <stdio.h>
main()
{
char str[50],*ptr,*lptr;
printf(“\nEnter string :”);
gets(str);
fflush(stdin);

for(lptr=str; *lptr !=’\0'; lptr++); /*reach the string terminator


*/

lptr--;/*position on the last character */

for(ptr=str; ptr<=lptr; lptr--,ptr++)


{
if(*ptr != *lptr)
break;
}
if(ptr>lptr)
printf(“%s is a palindrome”,str );
else
printf(“%s is not a palindrome",str);
}
Passing pointers to functions in C
C programming allows passing a pointer to a
function. To do so, simply declare the function
parameter as a pointer type.

Following is a simple example where we pass an


unsigned long pointer to a function and change
the value inside the function which reflects
back in the calling function −
#include <stdio.h>
#include <time.h>

void getSeconds(unsigned long *par);

int main ()
{
unsigned long sec;
getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}

void getSeconds(unsigned long *par) {


/* get the current number of seconds */
*par = time( NULL );
return;
}
#include <stdio.h>
/* function declaration */
double getAverage(int *arr, int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf("Average value is: %f\n", avg );
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}

avg = (double)sum / size;


return avg;
Pointer to a function
Function pointers in C are variables that can
store the memory address of functions and can
be used in a program to create a function call to
functions pointed by them.

Function pointers in C need to be declared with


an asterisk symbol and function parameters
(same as the function they will point to) before
using them in the program.

Declaration of function pointers in C includes


the return type and data type of different
function arguments.
Like variables, instructions of a function are also
stored in memory and have an address. A pointer
pointing to the address of a function is
called function pointer. A function pointer in C can be
used to create function calls to the function they
point to just like a normal function. Example:

#include <stdio.h>
void test() {
// test function that does nothing
return ;
}

int main() {
int a = 5;
// printing the address of variable a
printf("Address of variable = %p\n", &a);

// printing the address of function main()


printf("Address of a function = %p", test);
return 0;
}
Syntax of Function Pointer in C
return_type (* pointer_name) (datatype_arg_1,
datatype_arg_1, ...);

Example :
void *(*fp) (int *, int *);

At first glance, this example seems complex but


the trick to understanding such declarations is
to read them inside out. Here, (*fp) is a
function pointer just like normal pointer in C
like int *ptr. This function pointer (*fp) can
point to functions with two int * type arguments
and has a return type of void * as we can see
from its declaration where (int *, int *) explains
the type and number of arguments ans void * is
the return type from the pointed function.
Calling a Function Through a Function Pointer in C

Calling a function using a pointer is similar to calling a


function in the usual way using the name of the function.

int (*pointer) (int); // function pointer declaration


int areaSquare (int); // function declaration
pointer = areaSquare;

To call the function areaSquare, we can create a


function call using any of the three ways.

int length = 5;
// Different ways to call the function

// 1. using function name


int area = areaSquare(length);

// 2. using function pointer (a)


int area = (*pointer)(length);

// 3. using function pointer (b)


int area = pointer(length);
#include<stdio.h>

// function declaration
int areaRectangle(int, int);

int main() {
int length, breadth, area;

/* function pointer declaration note that our pointer declaration has identical
arguments as the function it will point to
int (*fp)(int, int);

printf("Enter length and breadth of a rectangle\n");


scanf("%d%d", &length, &breadth);

// pointing the pointer to functions memory address


fp = areaRectangle;

// calling the function using function pointer


area = (*fp)(length, breadth);

printf("Area of rectangle = %d", area);


return 0;
}

// function definition
int areaRectangle(int l, int b) {
int area_of_rectangle = l * b;
return area_of_rectangle;
}
Example: Array of function pointers

Arrays are data structure that stores collection


of identical data types. Like any other data types
we can create an array to store function pointers
in C.

Function pointers can be accessed from their


indexes like we access normal array values arr[i].

This way we are creating an array of function


pointers, where each array element stores a
function pointer pointing to different functions.

This approach is useful when we do not know in


advance which function is called, as shown in the
example.
#include<stdio.h>

float add(int, int);


float multiply(int,int);
float divide(int,int);
float subtract(int,int);

int main() {
int a, b;
float (*operation[4])(int, int);

operation[0] = add;
operation[1] = subtract;
operation[2] = multiply;
operation[3] = divide;

printf("Enter two values ");


scanf("%d%d", &a, &b);

float result = (*operation[0])(a, b);


printf("Addition (a+b) = %.1f\n", result);
result = (*operation[1])(a, b);
printf("Subtraction (a-b) = %.1f\n", result);

result = (*operation[2])(a, b);


printf("Multiplication (a*b) = %.1f\n", result);

result = (*operation[3])(a, b);


printf("Division (a/b) = %.1f\n", result);

return 0;
}

float add(int a, int b) {


return a + b;
}

float subtract(int a, int b) {


return a - b;
}

float multiply(int a, int b) {


return a * b;
}

float divide(int a, int b) {


return a / (b * 1.0);
}
Dynamic Memory Allocation
Dynamic memory allocation in C refers to the
process of allocating memory for variables or
data structures during runtime, as opposed
to static memory allocation where memory is
allocated at compile time.

It's done using functions like malloc(),


calloc(), and realloc(). Remember to free the
allocated memory using the free() function
to avoid memory leaks.

There are above 4 library functions provided


by C defined under header file to facilitate
dynamic memory allocation in C programming.
malloc() function
The “malloc” or “memory allocation” method in
C is used to dynamically allocate a single large
block of memory with the specified size. It
returns a pointer of type void which can be cast
into a pointer of any form.

It doesn’t Initialize memory at execution time


so that it has initialized each block with the
default garbage value initially.

Syntax of malloc() in C

ptr = (cast-type*) malloc(byte-size)


For Example:
Int *ptr = (int*) malloc(5 * sizeof(int));

Since the size of int is 4 bytes, this statement


will allocate 20 bytes of memory. And, the
pointer ptr holds the address of the first byte
in the allocated memory.

If space is insufficient, allocation fails and


returns a NULL pointer
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
//This pointer will hold the base address of the block Created
int *ptr;
int n, i;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("\nMemory allocated successfully");
printf("\n intializing the elements of the array.....");

for(i=0;i<n;i++)
{
ptr[i]=i+1;
}

printf("\n Printing the elements of the array.....\n");

for(i=0;i<n;i++)
{
printf("%d ",ptr[i]);
}
int k;
printf("\nEnter new size of Dynamic Array........");
scanf("%d",&k);

ptr=(int *)realloc(ptr,k*sizeof(int));

for(i=n;i<k;i++)
{
ptr[i]=i+1;
}

printf("\n");

for(i=0;i<k;i++)
{
printf("%d ",ptr[i]);
}
free(ptr);
}
return 0;
}
C calloc() function
 “calloc” or “contiguous allocation” method in C is
used to dynamically allocate the specified
number of blocks of memory of the specified
type. it is very much similar to malloc() but has
two different points and these are:

 It initializes each block with a default value ‘0’.

 It has two parameters or arguments as compare


to malloc().

Syntax of calloc() in C

ptr = (cast-type*)calloc(n, element-size);

here, n is the no. of elements and element-size is


the size of each element.
For Example:
ptr = (float*) calloc(5, sizeof(float));
This statement allocates contiguous space in
memory for 5 elements each with the size of the
float.

If space is insufficient, allocation fails and


returns a NULL pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the base address of the block
created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;

printf("Enter number of elements: %d\n", n);


// Dynamically allocate memory using calloc()

ptr = (int*)calloc(n, sizeof(int));


// Check if the memory has been successfully
// allocated by calloc or not

if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array

for (i = 0; i < n; ++i)


{
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");

for (i = 0; i < n; ++i)


{
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
free() function
“free” method in C is used to dynamically de-allocate the
memory. The memory allocated using functions malloc()
and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to
reduce wastage of memory by freeing it.

Syntax of free() in C
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main()
{ // This pointer will hold the base address of the
//block created
int *ptr, *ptr1;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()

ptr = (int*)malloc(n * sizeof(int));


// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);

printf("Calloc Memory successfully freed.\n");


}
return 0;
}
realloc() function
“realloc” or “re-allocation” method in C is used
to dynamically change the memory allocation of
a previously allocated memory.

In other words, if the memory previously


allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically
re-allocate memory. reallocation of memory
maintains the already present value and new
blocks will be initialized with the default
garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a


NULL pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the base address of the block
created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not

if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

// Get the new size for the array


n = 10;

printf("\n\nEnter the new size of the array: %d\n", n);


// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));

// Memory has been successfully allocated


printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array


for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

free(ptr);
}
return 0;
}
Exercises
Exercise 1
Write a program that accepts 2 strings and displays
the position where the second string occurs in the
first. Display 0 if the second string does not occur in
the first.

Exercise 2
Write a function to accept and sort a string in
ascending order of its elements.

Exercise 3

Write programs to do the following:


1.Copy the contents of a string str2 into str1.
2.Add the contents of a string str2 to the
contents of str1.

where str1 and str2 are arrays of type char.


Expression
You can use the #define directive to define a constant
using an expression.

For example:

#define AGE (28 / 2)


In this example, the constant named AGE would also
contain the value of 14.

#include <stdio.h>
#define NAME “CIMAGE "
#define AGE 14
#define MIN(a,b) ((a)<(b)?(a):(b))

int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
printf("Minimum between 10 and 20 is:%d\n",MIN(10,20));
return 0;
}
# include<stdio.h>
# define ERRORS 5

char *err_msg[]= {
/*Note the missing index*/
“All's well”,
“File not found”,
“No read permission for file”,
“Insufficient memory”,
“No write permission for file”
};
main()
{
int err_no;
for ( err_no = 0; err_no < ERRORS; err_no++ )
{
printf (“\nError message %d is : %s\n”, err_no + 1,
err_msg[err_no]);
}
}
Exercises
Exercise 1
Write a program that accepts 2 strings and displays
the position where the second string occurs in the
first. Display 0 if the second string does not occur in
the first.

Exercise 2
Write a function to accept and sort a string in
ascending order of its elements.

Exercise 3
Write programs to do the following:
1.Copy the contents of a string str2 into
str1.
2.Add the contents of a string str2 to the
contents of str1.
where str1 and str2 are arrays of type char.

You might also like