SlideShare a Scribd company logo
Pointers in C
Pointers are one of the things that make C stand out from
other programming languages
They are important in C, because they allow us to manipulate
the data in the computer's memory. This can reduce the code
and improve the performance.
As the pointers in C store the memory addresses, their size is
independent of the type of data they are pointing to.
The size of the pointers in C only depends on the system
architecture.
Declaration of Pointers in C
A pointer is a variable that stores the memory address of
another variable as its value.
A pointer variable points to a data type (like int) of the
same type, and is created with the * operator.
The address of the variable you are working with is
assigned to the pointer
Syntax: type *var-name;
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character
Syntax of C Pointers
• The syntax of pointers is similar to the variable
declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
• datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
How to Use Pointers?
The use of pointers in C can be divided into three
steps:
• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
Pointer Declaration
• In pointer declaration, we only declare the
pointer but do not initialize it. To declare a
pointer, we use the ( * ) dereference
operator before its name.
• int *ptr;
• The pointer declared here will point to some
random memory address as it is not initialized.
Such pointers are called wild pointers.
Pointer Initialization
• Pointer initialization is the process where we assign some initial value to
the pointer variable. We generally use the ( & ) addressof operator to get
the memory address of a variable and then store it in the pointer variable.
• int var = 10;
• int * ptr;
• ptr = &var;
• We can also declare and initialize the pointer in a single step. This method
is called pointer definition as the pointer is declared and initialized at the
same time.
Eg :int *ptr = &var;
Pointer Dereferencing
• Dereferencing a pointer is the process of
accessing the value stored in the memory
address specified in the pointer. We use the
same ( * ) dereferencing operator that we used in
the pointer declaration.
Pointer Dereferencing
Pointer to Pointer
• Declaration
– Place an additional asterisk
newbalance is a pointer to a float pointer.
9
double **newbalance;
Pointer to Pointer contd..
{program: pointers.c}
10
#include <stdio.h>
int main() {
int x, *p, **q;
x = 10;
p = &x;
q = &p;
printf(“%d %d %dn”, x, *p, **q);
return 0;
}
Sample Program
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %xn", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %xn", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %dn", *ip );
return 0;
}
NULL Pointers
• 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.
• The NULL pointer is a constant with a value of zero defined in
several standard libraries.
NULL Pointers
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %xn", ptr );
return 0;
}
Passing pointers to function
14
Int main()
{
int x=5;
……………..
…………..
foo(&x);
}
void foo(int *a)
{
int m;
m=*a;
m=m+1;
*a=m;
}
x
5
&x=1400
1400
a
*a
1400
Call by value
15
Int main()
{
int x=10, y=5;
swap(x,y);
}
swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
x y
10 5
a b
10 5
Call by Reference
16
Int main()
{
int x=10, y=5;
swap(&x,&y);
}
swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
x y
10 5
1400 1500
a b
1400 1500
*a
*b
Sample Program call by value
#include <stdio.h>
// function declaration
void add10(int);
int main(void)
{
// integer variable
int num = 10;
// print value of num
printf("Value of num before function call: %dn", num);
// pass by value
add10(num);
// print value of num
printf("Value of num after function call: %dn", num);
return 0; }
// function definition
void add10(int n)
{ n = n + 10;
printf("Inside add10(): Value %dn", n);
}
Sample Program call by Reference
#include <stdio.h>
// function declaration
void add10(int *);
int main(void)
{
// integer variable I
nt num = 10;
// print value of num
printf("Value of num before function call: %dn", num);
// pass by reference
add10(&num);
// print value of num
printf("Value of num after function call: %dn", num);
return 0; }
// function definition
void add10(int *n)
{ *n = *n + 10;
printf("Inside add10(): Value %dn", *n);
}
Dynamic Memory Allocation in C
• Dynamic Memory Allocation refers to the process of allocating or
deallocating memory blocks during a program’s runtime. This is achieved
through the use of four functions:
Dynamic Memory Allocation in C
These functions are located in the <stdlib.h> header file.
Dynamic memory allocation can also be considered as a method
of utilizing heap memory, where the size of variables or data
structures (such as arrays) can be changed during a program’s
execution with the help of these library functions.
21
Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory.
• free
– Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
• We will only do malloc and free
22
Allocating a Block of Memory
• A block of memory can be allocated using the
function malloc
– Reserves a block of memory of specified size and
returns a pointer of type void
– The return pointer can be type-casted to any
pointer type
• General format:
type *p;
p = (type *) malloc (byte_size);
23
Example
p = (int *) malloc(100 * sizeof(int));
– A memory space equivalent to 100 times the
size of an int bytes is reserved
– The address of the first byte of the allocated
memory is assigned to the pointer p of type int
p
400 bytes of space
24
Contd.
• cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr of type char
• sptr = (struct stud *) malloc(10*sizeof(struct stud));
Allocates space for a structure array of 10 elements. sptr points to
a structure element of type struct stud
Always use sizeof operator to find number of bytes for a data type, as it can vary
from machine to machine
25
Points to Note
• malloc always allocates a block of contiguous bytes
– The allocation can fail if sufficient contiguous memory space
is not available
– If it fails, malloc returns NULL
if ((p = (int *) malloc(100 * sizeof(int))) == NULL)
{
printf (“n Memory cannot be allocated”);
exit();
}
26
Example
printf("Input heights for %d
students n",N);
for (i=0; i<N; i++)
scanf ("%f", &height[i]);
for(i=0;i<N;i++)
sum += height[i];
avg = sum / (float) N;
printf("Average height = %f n",
avg);
free (height);
return 0;
}
int main()
{
int i,N;
float *height;
float sum=0,avg;
printf("Input no. of studentsn");
scanf("%d", &N);
height = (float *)
malloc(N * sizeof(float));
Calloc() Method
The calloc() function in C is used to dynamically allocate
a contiguous block of memory in the heap section.
Unlike malloc(), calloc() is used to allocate multiple
blocks of memory, typically to store an array of
elements.
Syntax
The syntax of calloc() function in C is shown below:
(cast-type*) calloc(n, size);
cast-type is the type you want to cast the allocated
memory to (for example, int* or float*)
n is the number of blocks to be allocated
size is the size of each block in bytes
Realloc() Method
realloc() is a function in C that allows you to change the size of a
previously allocated memory block. This function can be used to
increase or decrease the size of a block of memory that was
previously allocated using either malloc() or calloc(). It can also
be used to completely allocate or de-allocate a memory block on
its own.
Syntax
The syntax of realloc() function in C is shown below:
void *realloc(void *ptr, size_t size);
ptr is a pointer to the memory block previously allocated using
malloc() or calloc().
size is the new size for the memory block, in bytes. The function
returns a pointer to the newly allocated memory block. If the
reallocation fails, the function returns NULL.
Free() Method
The free() method in C is used to deallocate a memory
block previously allocated by malloc() or calloc() functions
during the execution of the program. It frees up the
occupied memory so that it can be reused again.
Syntax
The syntax of free() function in C is shown below:
void free(void *ptr);
Here, ptr is a pointer to the memory block that needs to be
deallocated.
#include<stdio.h>
int main()
{
int *p,n,i,
max=-32768,min=32767;
printf("entersize:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("enterelements:");
for(i=0;i<n;i++){
scanf("%d",p+i);
if(*(p+i)>max)
max=*(p+i);
if(*(p+i)<min)
min=*(p+i); }
printf("maximum=%dminimum=%d",max,min);
free(p);
}
Structure and Union
Structure
Structures (also called struts) are used to
group several related variables into one place.
Each variable in the structure is known as
a member of the structure.
How it differs from an Array?
• An array contains values of same data type
• A structure can contain many different data
types (int, float, char, etc.).
Creating a Structure
struct MyStructure { // Structure declaration
datatype variable1; // Member
datatype variable2; // Member
}; // End the structure with a semicolon
Accessing a Structure
Creating a structure variable
struct Student{
int rollNum;
char name[10];
};
void main() {
struct Student s1;
}
Accessing a Structure
Assigning values to members of a structure:
Struct student s1;
struct student s2;
s1.rollNum =13;
s2.rollNum=15;
S1.name=“Priya”;
S2.name=“Arun”;
Initializing structure variables
struct myStructure s1 = {13, 'B', "Some text"};
printf("%d %c %s", s1.myNum, s1.myLetter,
s1.myString);
Example
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %dn", car1.brand, car1.model, car1.year);
printf("%s %s %dn", car2.brand, car2.model, car2.year);
printf("%s %s %dn", car3.brand, car3.model, car3.year);
return 0;
}
Union
The Union is a user-defined data type in C
language that can contain elements of the
different data types just like structure. But
unlike structures, all the members in the C
union are stored in the same memory
location. Due to this, only one member can
store data at the given instance.
Difference between structure and union
Union Declaration
union union_name
{
datatype member1;
datatype member2; ...
};
Different Ways to Define a Union Variable
Defining Union Variable with Declaration:
union union_name
{
datatype member1;
datatype member2; ...
}
var1, var2, ...;
Different Ways to Define a Union Variable
Defining Union Variable after Declaration:
union union_name var1, var2, var3...;
Example
union un
{
int member1;
char member2;
float member3;
};
int main()
{
union un var1;
var1.member1 = 15;
printf("The value stored in member1 = %d",
var1.member1);
return 0;
List of Experiment
1. Create a Structure called Employee which stores the
name, id, basic pay, HRA and DA as members. Find the
total pay of the employee.
2. Create an Union called Student with name, class,
rollnum, total marks as members. Find and display the
grade of each student.
>80 – Grade A
>60 – Grade B
> 50 – Grade C
<50 - Fail

More Related Content

Similar to pointers in c programming - example programs (20)

PDF
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
PPTX
Dynamic Memory Allocation.pptx
ssuser688516
 
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
SKUP1
 
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
LECO9
 
PPTX
C Programming Unit-4
Vikram Nandini
 
PPTX
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Selvaraj Seerangan
 
PDF
dynamic-allocation.pdf
ngonidzashemutsipa
 
PPT
pointers (1).ppt
Osmania University
 
PPTX
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
TriggeredZulkar
 
PPTX
Structures_and_Files[1] - Read-Only.pptx
Ramesh Bssv
 
PPT
358 33 powerpoint-slides_3-pointers_chapter-3
sumitbardhan
 
PDF
C for Java programmers (part 2)
Dmitry Zinoviev
 
PPT
ch08.ppt
NewsMogul
 
PPTX
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
PDF
VIT351 Software Development VI Unit3
YOGESH SINGH
 
PPTX
pointers.pptx
s170883BesiVyshnavi
 
DOCX
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
PPTX
Advance topics of C language
Mehwish Mehmood
 
PPT
79744777- FULL AND DETAILED LEVEL OF Pointers-in-c-Presentation.ppt
persis10
 
PPTX
dynamic_v1-3.pptx
ngonidzashemutsipa
 
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
Dynamic Memory Allocation.pptx
ssuser688516
 
DYNAMIC MEMORY ALLOCATION.pptx
SKUP1
 
DYNAMIC MEMORY ALLOCATION.pptx
LECO9
 
C Programming Unit-4
Vikram Nandini
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Selvaraj Seerangan
 
dynamic-allocation.pdf
ngonidzashemutsipa
 
pointers (1).ppt
Osmania University
 
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
TriggeredZulkar
 
Structures_and_Files[1] - Read-Only.pptx
Ramesh Bssv
 
358 33 powerpoint-slides_3-pointers_chapter-3
sumitbardhan
 
C for Java programmers (part 2)
Dmitry Zinoviev
 
ch08.ppt
NewsMogul
 
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
VIT351 Software Development VI Unit3
YOGESH SINGH
 
pointers.pptx
s170883BesiVyshnavi
 
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
Advance topics of C language
Mehwish Mehmood
 
79744777- FULL AND DETAILED LEVEL OF Pointers-in-c-Presentation.ppt
persis10
 
dynamic_v1-3.pptx
ngonidzashemutsipa
 

Recently uploaded (20)

PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Day2 B2 Best.pptx
helenjenefa1
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Ad

pointers in c programming - example programs

  • 1. Pointers in C Pointers are one of the things that make C stand out from other programming languages They are important in C, because they allow us to manipulate the data in the computer's memory. This can reduce the code and improve the performance. As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. The size of the pointers in C only depends on the system architecture.
  • 2. Declaration of Pointers in C A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int) of the same type, and is created with the * operator. The address of the variable you are working with is assigned to the pointer Syntax: type *var-name; int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character
  • 3. Syntax of C Pointers • The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration. • datatype * ptr; where • ptr is the name of the pointer. • datatype is the type of data it is pointing to.
  • 4. How to Use Pointers? The use of pointers in C can be divided into three steps: • Pointer Declaration • Pointer Initialization • Pointer Dereferencing
  • 5. Pointer Declaration • In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. • int *ptr; • The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.
  • 6. Pointer Initialization • Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable. • int var = 10; • int * ptr; • ptr = &var; • We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time. Eg :int *ptr = &var;
  • 7. Pointer Dereferencing • Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.
  • 9. Pointer to Pointer • Declaration – Place an additional asterisk newbalance is a pointer to a float pointer. 9 double **newbalance;
  • 10. Pointer to Pointer contd.. {program: pointers.c} 10 #include <stdio.h> int main() { int x, *p, **q; x = 10; p = &x; q = &p; printf(“%d %d %dn”, x, *p, **q); return 0; }
  • 11. Sample Program #include <stdio.h> int main () { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("Address of var variable: %xn", &var ); /* address stored in pointer variable */ printf("Address stored in ip variable: %xn", ip ); /* access the value using the pointer */ printf("Value of *ip variable: %dn", *ip ); return 0; }
  • 12. NULL Pointers • 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. • The NULL pointer is a constant with a value of zero defined in several standard libraries.
  • 13. NULL Pointers #include <stdio.h> int main () { int *ptr = NULL; printf("The value of ptr is : %xn", ptr ); return 0; }
  • 14. Passing pointers to function 14 Int main() { int x=5; …………….. ………….. foo(&x); } void foo(int *a) { int m; m=*a; m=m+1; *a=m; } x 5 &x=1400 1400 a *a 1400
  • 15. Call by value 15 Int main() { int x=10, y=5; swap(x,y); } swap(int a, int b) { int temp; temp=a; a=b; b=temp; } x y 10 5 a b 10 5
  • 16. Call by Reference 16 Int main() { int x=10, y=5; swap(&x,&y); } swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } x y 10 5 1400 1500 a b 1400 1500 *a *b
  • 17. Sample Program call by value #include <stdio.h> // function declaration void add10(int); int main(void) { // integer variable int num = 10; // print value of num printf("Value of num before function call: %dn", num); // pass by value add10(num); // print value of num printf("Value of num after function call: %dn", num); return 0; } // function definition void add10(int n) { n = n + 10; printf("Inside add10(): Value %dn", n); }
  • 18. Sample Program call by Reference #include <stdio.h> // function declaration void add10(int *); int main(void) { // integer variable I nt num = 10; // print value of num printf("Value of num before function call: %dn", num); // pass by reference add10(&num); // print value of num printf("Value of num after function call: %dn", num); return 0; } // function definition void add10(int *n) { *n = *n + 10; printf("Inside add10(): Value %dn", *n); }
  • 19. Dynamic Memory Allocation in C • Dynamic Memory Allocation refers to the process of allocating or deallocating memory blocks during a program’s runtime. This is achieved through the use of four functions:
  • 20. Dynamic Memory Allocation in C These functions are located in the <stdlib.h> header file. Dynamic memory allocation can also be considered as a method of utilizing heap memory, where the size of variables or data structures (such as arrays) can be changed during a program’s execution with the help of these library functions.
  • 21. 21 Memory Allocation Functions • malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free – Frees previously allocated space. • realloc – Modifies the size of previously allocated space. • We will only do malloc and free
  • 22. 22 Allocating a Block of Memory • A block of memory can be allocated using the function malloc – Reserves a block of memory of specified size and returns a pointer of type void – The return pointer can be type-casted to any pointer type • General format: type *p; p = (type *) malloc (byte_size);
  • 23. 23 Example p = (int *) malloc(100 * sizeof(int)); – A memory space equivalent to 100 times the size of an int bytes is reserved – The address of the first byte of the allocated memory is assigned to the pointer p of type int p 400 bytes of space
  • 24. 24 Contd. • cptr = (char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char • sptr = (struct stud *) malloc(10*sizeof(struct stud)); Allocates space for a structure array of 10 elements. sptr points to a structure element of type struct stud Always use sizeof operator to find number of bytes for a data type, as it can vary from machine to machine
  • 25. 25 Points to Note • malloc always allocates a block of contiguous bytes – The allocation can fail if sufficient contiguous memory space is not available – If it fails, malloc returns NULL if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“n Memory cannot be allocated”); exit(); }
  • 26. 26 Example printf("Input heights for %d students n",N); for (i=0; i<N; i++) scanf ("%f", &height[i]); for(i=0;i<N;i++) sum += height[i]; avg = sum / (float) N; printf("Average height = %f n", avg); free (height); return 0; } int main() { int i,N; float *height; float sum=0,avg; printf("Input no. of studentsn"); scanf("%d", &N); height = (float *) malloc(N * sizeof(float));
  • 27. Calloc() Method The calloc() function in C is used to dynamically allocate a contiguous block of memory in the heap section. Unlike malloc(), calloc() is used to allocate multiple blocks of memory, typically to store an array of elements. Syntax The syntax of calloc() function in C is shown below: (cast-type*) calloc(n, size); cast-type is the type you want to cast the allocated memory to (for example, int* or float*) n is the number of blocks to be allocated size is the size of each block in bytes
  • 28. Realloc() Method realloc() is a function in C that allows you to change the size of a previously allocated memory block. This function can be used to increase or decrease the size of a block of memory that was previously allocated using either malloc() or calloc(). It can also be used to completely allocate or de-allocate a memory block on its own. Syntax The syntax of realloc() function in C is shown below: void *realloc(void *ptr, size_t size); ptr is a pointer to the memory block previously allocated using malloc() or calloc(). size is the new size for the memory block, in bytes. The function returns a pointer to the newly allocated memory block. If the reallocation fails, the function returns NULL.
  • 29. Free() Method The free() method in C is used to deallocate a memory block previously allocated by malloc() or calloc() functions during the execution of the program. It frees up the occupied memory so that it can be reused again. Syntax The syntax of free() function in C is shown below: void free(void *ptr); Here, ptr is a pointer to the memory block that needs to be deallocated.
  • 32. Structure Structures (also called struts) are used to group several related variables into one place. Each variable in the structure is known as a member of the structure. How it differs from an Array? • An array contains values of same data type • A structure can contain many different data types (int, float, char, etc.).
  • 33. Creating a Structure struct MyStructure { // Structure declaration datatype variable1; // Member datatype variable2; // Member }; // End the structure with a semicolon
  • 34. Accessing a Structure Creating a structure variable struct Student{ int rollNum; char name[10]; }; void main() { struct Student s1; }
  • 35. Accessing a Structure Assigning values to members of a structure: Struct student s1; struct student s2; s1.rollNum =13; s2.rollNum=15; S1.name=“Priya”; S2.name=“Arun”;
  • 36. Initializing structure variables struct myStructure s1 = {13, 'B', "Some text"}; printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
  • 37. Example struct Car { char brand[50]; char model[50]; int year; }; int main() { struct Car car1 = {"BMW", "X5", 1999}; struct Car car2 = {"Ford", "Mustang", 1969}; struct Car car3 = {"Toyota", "Corolla", 2011}; printf("%s %s %dn", car1.brand, car1.model, car1.year); printf("%s %s %dn", car2.brand, car2.model, car2.year); printf("%s %s %dn", car3.brand, car3.model, car3.year); return 0; }
  • 38. Union The Union is a user-defined data type in C language that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given instance.
  • 40. Union Declaration union union_name { datatype member1; datatype member2; ... };
  • 41. Different Ways to Define a Union Variable Defining Union Variable with Declaration: union union_name { datatype member1; datatype member2; ... } var1, var2, ...;
  • 42. Different Ways to Define a Union Variable Defining Union Variable after Declaration: union union_name var1, var2, var3...;
  • 43. Example union un { int member1; char member2; float member3; }; int main() { union un var1; var1.member1 = 15; printf("The value stored in member1 = %d", var1.member1); return 0;
  • 44. List of Experiment 1. Create a Structure called Employee which stores the name, id, basic pay, HRA and DA as members. Find the total pay of the employee. 2. Create an Union called Student with name, class, rollnum, total marks as members. Find and display the grade of each student. >80 – Grade A >60 – Grade B > 50 – Grade C <50 - Fail