PSC-unit 4
PSC-unit 4
Structures and unions - accessing structure members arrays within structures, arrays of
structures, structures within structures,passing structures as function arguments. Type defining
structures,Pointers: Pointer variables. Declaring and dereferencing pointer variables. Pointer
Arithmetic. Examples. Accessing arrays through pointers. Pointers and strings. Pointers to
Functions (call by value and call by reference -Pointers to Arrays, Pointers to Structures,
Dynamic memory allocation.
4.1 Structures
In C, there are cases where we need to store multiple attributes of an entity. It is not necessary
that an entity has all the information of one type only. It can have different attributes of different
data types.
For example, an entity Student may have its name (string), roll number (int), marks (float). To
store such type of information, we use a special data structure called “Structure”.
What is Structure?
Structure in C is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member.
struct structure_name
{
data_type member1;
data_type member2;
..
..
data_type memberN;
};
struct employee
{ int id;
char name[20] ;
char company[100] ;
};
The following image shows the memory allocation of the structure employee that is defined in
the above example.
id, name, and salary are the members or fields of the structure.
We can declare a variable for the structure so that we can access the member of the structure
easily. There are two ways to declare structure variable:
Let's see the example to declare the structure variable by struct keyword. It should be declared
within the main function.
struct employee
{ int id;
char name[50] ;
char company[100] ;
};
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and
e2 can be treated in the same way as the objects in C++ and Java.
2nd way:
Another way to declare structure variable is at the time of defining the structure.
struct employee
{ int id;
char name[50];
char company[100] ;
} e1, e2;
If the number of variables is not fixed, the first approach can be used. It provides the flexibility
to declare the structure variable many times.
The following statement is used to access the structure member “id” of variable p1, using .
(member) operator.
p1.id
C Structure Example
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
} e1; //declaring structure variable, e1
int main()
{
//store first employee information
e1.id=101;
strcpy (e1.name, "Ganesh");//copying string into char array
//printing first employee information
printf( "Employee 1 id : %d", e1.id);
printf( "Employee 1 name : %s", e1.name);
return 0;
}
Output:
Let's see another example of the structure in C language to store many employees information.
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name [50];
float salary;
} e1, e2; // declaring structure variables, e1 and e2
int main ()
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Harishva");//copying string into char array
e1.salary=150000;
Output:
employee 1 id : 101
employee 1 name : Harishva
employee 1 salary : 150000
employee 2 id : 102
employee 2 name : Krithik
employee 2 salary : 140000
An array can be declared inside a structure as a member when we need to store multiple
members of the same type.
For example, suppose we have an employee and we need to store the data of his/her weekly
attendance. So for that, we need to define a structure of type Employee and store the data
within that.
struct Employee
{
int day1, day2, day3, day4, day5, day6, day7;
};
struct StructureName {
// Other members
dataType arrayName[arraySize];
};
structureName.arrayName[index]
#include <string.h>
#include <stdio.h>
// Defining array within structure
struct Employee
{
// character array to store name of the employee
char Name[20];
int employeeID;
// integer array to maintain the record of attendanc eof
// the employee
int WeekAttendence[7];
};
int main()
{
// defining structure of type Employee
struct Employee emp;
// Adding data
emp.employeeID = 1;
strcpy(emp.Name, "Rohit");
int week;
for (week = 0; week < 7; week++) {
int attendence;
emp.WeekAttendence[week] = week;
}
printf("\n");
// printing the data
printf("Emplyee ID: %d - Employee Name: %s\n",
emp.employeeID, emp.Name);
printf("Attendence\n");
for (week = 0; week < 7; week++) {
printf("%d ", emp.WeekAttendence[week]);
}
printf("\n");
return 0;
}
Output
Emplyee ID: 1 - Employee Name: Rohit
Attendence
0123456
4.3 ARRAYS OF STRUCTURES
An array of structures in C can be defined as the collection of multiple structures variables
where each variable contains information about different entities. The array of structures in
C are used to store information about multiple entities of different data types.
The array of structures is also known as collection of structures.
Output:
The member of a nested structure can be accessed using the following syntax:
Variable name of Outer_Structure.Variable name of Nested_Structure.data member to
access
Example 1:
The following program shows how to pass an entire structure as an argument to function.
#include<stdio.h>
struct date
{
int day;
char month[10];
int year;
};
int main()
{
struct date d;
printf("enter the day,month and year:");
scanf("%d%s%d", &d.day, d.month, &d.year);
display(d);//passing entire structure as an argument to function
return 0;
}
void display (struct date d)
{
printf("day=%d", ,d.day);
printf("month=%s", d.month);
printf("year=%d", d.year);
}
ADVERTISEMENT
Output
Example 2
Consider another example that demonstrate the passing of an entire structure as an argument
to function.
#include<stdio.h>
struct add{
int var1;
int var2;
}a;
//Declaring and returning Function //
void show(struct add a)
{
//Declaring sum variable//
int sum;
//Arithmetic Operation//
sum=a.var1+a.var2;
//Printing O/p //
printf("Added value is %d",sum);
}
void main()
{
//Declaring structure//
struct add a;
//Reading User I/p
printf("Enter variable 1 = ");
scanf("%d”, &a.var1);
printf("Enter variable 2 = ");
scanf("%d", &a.var2);
//Calling function //
show(a);
}
Output
Enter variable 1 = 20
Enter variable 2 = 50
Added value is 70
4.6 TYPE DEFINING STRUCTURES
Using the typedef keyword:
There is no longer a need to type struct again and again with every declaration of the variable
of this type.
Method 1:
In the code below, the structure Point is defined separately using struct Point, and then
a typedef is applied to create an alias Point for this structure. This allows us to declare variables
of this structure type using just Point.
4
15
#include<stdio.h>
struct Point
{
int x;
int y;
};
typedef struct Point Point;
int main()
{
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d ", p1.x);
printf("%d ", p1.y);
return 0;
}
Run
Declaration of variable without mentioning struct again
1 3
Method 2:
The typedef is applied directly to the structure definition itself. This combines the definition of
the structure and the creation of the alias Point in a single statement.
#include<stdio.h>
// Define a structure named Point with two integer members: x and y
typedef struct Point{
int x;
int y;
} Point;
int main()
{
// Declare a variable named p1 of type Point
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
C program to implement typedef with structures
#include <stdio.h>
#include <string.h>
// Driver code
int main()
{
stu st;
strcpy(st.name, "HariShiva");
strcpy(st.branch, "Computer Science and Engineering");
st.ID_no = 108;
Output
Name: HariShva
Branch: Computer Science and Engineering
ID_no: 108
4.7 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.
Syntax of Union in C
union union_name
{
datatype member1;
datatype member2;
...
};
There are two methods using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name
{
datatype member1;
datatype member2;
...
} var1, var2, ...;
We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
Example of Union
// driver code
int main()
{
// defining a union variable
union un var1;
Output
The value stored in member1 = 15
Differences between Structure and Union
Array uses subscripts or '[ ]' (square Structure uses the '.' (dot operator) to access
2.
brackets) to access the elements the elements.
Traversing through and searching for Traversing through and searching for
4.
elements in an array is quick and easy. elements in a structure is slow and complex.
POINTER
4.8 What is a Pointer in C?
C pointer is the derived data type that is used to store the address of another variable and can
also be used to access and manipulate the variable's data stored at that location. The pointers
are considered as derived data types.
With pointers, you can access and modify the data located in the memory, pass the data
efficiently between the functions, and create dynamic data structures like linked lists, trees, and
graphs.
To declare a pointer, use the dereferencing operator (*) followed by the data type.
Syntax
The general form of a pointer variable declaration is
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer.
Example:
int *a;
int b=10;
a=&b;
Pointer Initialization
After declaring a pointer variable, you need to initialize it with the address of another variable
using the address of (&) operator. This process is known as referencing a pointer.
Syntax
The following is the syntax to initialize a pointer variable
pointer_variable = &variable;
Example
int x = 10;
int *ptr = &x;
Here, x is an integer variable, ptr is an integer pointer. The pointer ptr is being initialized with
x.
A pointer references a location in memory. Obtaining the value stored at that location is known
as dereferencing the pointer.
In C, it is important to understand the purpose of the following two operators in the context of
pointer mechanism
& Operator: It is also known as the "Address-of operator". It is used for Referencing
which means taking the address of an existing variable (using &) to set a pointer variable.
* Operator: It is also known as the "dereference operator". Dereferencing a pointer
is carried out using the * operator to get the value from the memory address that is pointed by
the pointer.
Pointers are used to pass parameters by reference. This is useful if a programmer wants a
function's modifications to a parameter to be visible to the function's caller. This is also useful
for returning multiple values from a function.
The value of the variable which is pointed by a pointer can be accessed and manipulated by
using the pointer variable. You need to use the asterisk (*) sign with the pointer variable to
access and manipulate the variable's value.
Example
In the below example, we are taking an integer variable with its initial value and changing it
with the new value.
#include <stdio.h>
int main()
{
int x = 10;
// Pointer declaration and initialization
int * ptr = & x;
// Printing the current value
printf("Value of x = %d\n", * ptr);
Output
Value of x = 10
Value of x = 20
4.11Pointer Arithmetic
C pointers arithmetic operations are different from the general arithmetic operations. The
following are some of the important pointer arithmetic operations in C:
"++" and "--" are used as the increment and decrement operators in C. They are unary operators,
used in prefix or postfix manner with numeric variable operands, and they increment or
decrement the value of the variable by one.
Assume that an integer variable "x" is created at address 1000 in the memory, with 10 as its
value. Then, "x++" makes the value of "x" as 11.
x++; // x becomes 11
What happens if we declare "y" as pointer to "x" and increment "y" by 1 (with "y++")? Assume
that the address of "y" itself is 2000.
#include <stdio.h>
int main(){
int x = 10;
int *y = &x;
y++;
#include <stdio.h>
int main(){
double x = 10;
double *y = &x;
y--;
#include <stdio.h>
int main(){
int a[]= {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int len = sizeof(a)/sizeof(int);
int *x = a;
int i = 0;
return 0;
}
Output:
Addition and subtraction of an integer to a pointer does not add and subtract that value to the
pointer, multiplication with the size of the data type is added or subtracted to the pointer.
For example, there is an integer pointer variable ptr and it is pointing to an address 123400, if
you add 1 to the ptr (ptr+1), it will point to the address 123404 (size of an integer is 4).
#include <stdio.h>
int main() {
int int_arr[] = {12, 23, 45, 67, 89};
int *ptrArr = int_arr;
// Adding 2 in ptrArr
ptrArr = ptrArr + 2;
return 0;
}
Output
Value at ptrArr: 12
Value at ptrArr after adding 2: 45
In the following example, we are declaring an array and pointer to an array. Initializing the
pointer with the last element of the array and then subtracting an integer value (2) from the
pointer to get the third element of the array.
#include <stdio.h>
int main() {
int int_arr[] = {12, 23, 45, 67, 89};
int *ptrArr = &int_arr[4]; // points to last element
// Subtracting 2 in ptrArr
ptrArr = ptrArr - 2;
return 0;
}
Output
Value at ptrArr: 89
Value at ptrArr after adding 2: 45
Subtraction of Pointers
We are familiar with the "+" and "−" operators when they are used with regular numeric
operands. However, when you use these operators with pointers, they behave in a little different
way.
Since pointers are fairly large integers (especially in modern 64-bit systems), addition of two
pointers is meaningless. When we add a 1 to a pointer, it points to the next location where an
integer may be stored. Obviously, when we add a pointer (itself a large integer), the location it
points may not be in the memory layout.
However, subtraction of two pointers is realistic. It returns the number of data types that can
fit in the two pointers.
Let us take the array in the previous example and perform the subtraction of pointers of a[0]
and a[9]
#include <stdio.h>
int main(){
int a[]= {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int *x = &a[0]; // zeroth element
int *y = &a[9]; // last element
Output
Comparison of Pointers
Pointers may be compared by using relational operators such as "==", "<", and ">". If "p1" and
"p2" point to variables that are related to each other (such as elements of the same array), then
"p1" and "p2" can be meaningfully compared.
#include <stdio.h>
const int MAX = 3;
int main() {
int var[] = {10, 100, 200};
int i, *ptr1, *ptr2;
// Initializing pointers
ptr1 = var;
ptr2 = &var[MAX - 1];
return 0;
}
Output:
Applications of Pointers in C
One of the most important features of C is that it provides low-level memory access with the
concept of pointers. A pointer is a variable that stores the address of another variable in the
memory.
The provision of pointers has many applications such as passing arrays and struct type to a
function and dynamic memory allocation, etc. In this chapter, we will explain some important
applications of pointers in C.
Array elements can also be accessed through the pointer. You need to declare and initialize a
pointer to an array and using it you can access each element by incrementing the pointer
variable by 1.
The pointer to an array is the address of its 0th element. When the array pointer is incremented
by 1, it points to the next element in the array.
Example
The following example demonstrates how you can traverse an array with the help of its pointer.
#include <stdio.h>
int main(){
return 0;
}
Output
Run the code and check its output −
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
arr[4]: 5
In C programming, pointers are a powerful tool that allow us to work with strings efficiently.
Strings in C are essentially arrays of characters terminated by a null character (\0). A pointer
to a string refers to the memory address where the string starts, and can be manipulated using
pointer arithmetic.
arduino
A pointer can also point to the first element of a string (character array). When we use pointers,
we can work with strings more flexibly.
Syntax:
In this case, str points to the memory location where the string "Hello" is stored. It is important
to note that strings declared this way are usually stored in a read-only section of memory, and
you should avoid modifying them.
We can use pointer arithmetic to navigate through the characters in a string. For example, if str
points to the first character of the string, str + 1 points to the second character, str + 2 to the
third, and so on.
Example:
#include <stdio.h>
int main() {
char *str = "Hello"; // Pointer to string
return 0;
}
Explanation:
Example:
#include <stdio.h>
int main() {
char str[] = "Hello"; // Modifiable character array
return 0;
}
Explanation:
• We modify the string through the pointer by dereferencing it (*ptr), and the changes
are reflected in the original string.
• *(ptr + 1) accesses the second character, allowing us to change it.
• Pointer to String:
o The string is stored in a read-only section, and modifying it can cause undefined
behavior.
o Example:
c
Copy code
char *str = "Hello"; // Do not modify this string!
• Array of Characters:
o The string is stored in modifiable memory (usually on the stack), and you can
modify the string.
o Example:
c
Copy code
char str[] = "Hello"; // Can be modified
6. Common String Operations using Pointers
Here are a few examples of common string operations done using pointers:
#include <stdio.h>
int main() {
char str[] = "Hello";
printf("Length of string: %d\n", stringLength(str)); // Output: 5
return 0;
}
2. Copying a String (strcpy):
#include <stdio.h>
int main() {
char src[] = "Hello";
char dest[10];
stringCopy(dest, src);
printf("Copied string: %s\n", dest); // Output: Hello
return 0;
}
Summary:
In call by value, the function receives a copy of the variable’s value. Any modifications made
to the parameter inside the function do not affect the original value.
Example: Call by Value with a Pointer to a Function
#include <stdio.h>
int main() {
// Assign the address of the 'add' function to 'func_ptr'
func_ptr = &add;
return 0;
}
In this example, the values of x and y are passed to the function pointer func_ptr, which points
to the add function. The values are passed by value, meaning the original values of x and y are
not modified.
In call by reference, the function receives a reference (pointer) to the variable, so any changes
made to the parameter inside the function will affect the original variable.
#include <stdio.h>
int main() {
// Assign the address of the 'swap' function to 'func_ptr'
func_ptr = &swap;
int x = 10, y = 20;
return 0;
}
In this example, the addresses of x and y are passed to the function pointer func_ptr, which
points to the swap function. Since the function operates on the addresses, it modifies the
original variables x and y.
Key Differences:
• Call by Value: The function receives copies of the arguments. Modifications inside the
function do not affect the original variables.
• Call by Reference: The function receives pointers to the arguments. Modifications
inside the function affect the original variables.
In C programming, the concepts of arrays and pointers have a very important role. There is
also a close association between the two. In this chapter, we will explain in detail the
relationship between arrays and pointers in C programming.
Arrays in C
An array in C is a homogenous collection of elements of a single data type stored in a
continuous block of memory. The size of an array is an integer inside square brackets, put in
front of the name of the array.
Declaring an Array
To declare an array, the following syntax is used
data_type arr_name[size];
Each element in the array is identified by a unique incrementing index, starting from "0". An
array can be declared and initialized in different ways.
You can declare an array and then initialize it later in the code, as and when required. For
example
int arr[5];
...
...
a[0] = 1;
a[1] = 2;
...
...
You can also declare and initialize an array at the same time. The values to be stored are put as
a comma separated list inside curly brackets.
#include <stdio.h>
int main()
{
int a[5], i;
return 0;
}
Output
a[0] = 712952649
a[1] = 32765
a[2] = 100
a[3] = 0
a[4] = 4096
Pointers in C
A pointer is a variable that stores the address of another variable. In C, the symbol (&) is used
as the address-of operator. The value returned by this operator is assigned to a pointer.
To declare a variable as a pointer, you need to put an asterisk (*) before the name. Also, the
type of pointer variable must be the same as the type of the variable whose address it stores.
In this code snippet, "b" is an integer pointer that stores the address of an integer variable "a"
−
int a = 5;
int *b = &a;
In case of an array, you can assign the address of its 0th element to the pointer.
int *b = arr;
Example: Increment Operator with Pointer
Unlike a normal numeric variable (where the increment operator "++" increments its value by
1), the increment operator used with a pointer increases its value by the sizeof its data type.
#include <stdio.h>
int main(){
int a = 5;
int *b = &a;
return 0;
}
Output
Run the code and check its output −
Address of a: 6422036
After increment, Address of a: 6422040
The Dereference Operator in C
In C, the "*" symbol is used as the dereference operator. It returns the value stored at the address
to which the pointer points.
Hence, the following statement returns "5", which is the value stored in the variable "a", the
variable that "b" points to.
int a = 5;
int *b = &a;
printf("value of a: %d\n", *b);
Note: In case of a char pointer, it will increment by 1; in case of a double pointer, it will
increment by 8; and in case of a struct type, it increments by the sizeof value of that struct type.
#include <stdio.h>
int main(){
b++;
printf("Address of a[1]: %d value at a[1] : %d\n", b, *b);
b++;
printf("Address of a[2]: %d value at a[2] : %d\n", b, *b);
b++;
printf("Address of a[3]: %d value at a[3] : %d\n", b, *b);
b++;
printf("Address of a[4]: %d value at a[4] : %d\n", b, *b);
return 0;
}
Output
Example
In this program, two strings are passed to the compare() function. A string in C is an array of
char data type. We use the strlen() function to find the length of the string.
#include <stdio.h>
int compare(char *, char *);
int main()
{
char str1[] = "BAT";
char str2[] = "BALL";
int ret = compare(str1, str2);
return 0;
}
int compare (char *x, char *y)
{
int val;
if (strlen(x) > strlen(y)){
printf("Length of Str1 is greater than or equal to the length of Str2");
}
Else
{
printf("Length of Str1 is less than the length of Str2");
}
}
Output
When you run this code, it will produce the following output −
If you have defined a derived data type using the keyword struct, then you can declare a
variable of this type. Hence, you can also declare a pointer variable to store its address. A
pointer to struct is thus a variable that refers to a struct variable.
struct name
{
member1;
member2;
.
.
};
You can then declare a pointer variable and store the address of var. To declare a variable as a
pointer, it must be prefixed by "*"; and to obtain the address of a variable, we use the "&"
operator.
To access the elements of a structure with pointer, we use a special operator called the
indirection operator (→) .
Here, we define a user-defined struct type called book. We declare a book variable and a
pointer.
struct book
char title[10];
double price;
int pages;
};
strptr = &b1;
In C programming, we use the indirection operator ("→") with struct pointers. It is also called
the "struct dereference operator". It helps to access the elements of a struct variable to which
the pointer references to.
The struct pointer uses the indirection operator or the dereference operator to fetch the values
of the struct elements of a struct variable. The dot operator (".") is used to fetch the values with
reference to the struct variable. Hence,
Open Compiler
#include <stdio.h>
#include <string.h>
struct book{
char title[10];
double price;
int pages;
};
int main(){
strptr = &b1;
return 0;
Output
Title: Learn C
Price: 675.500000
No of Pages: 325
Since C is a structured language, it has some fixed rules for programming. One of them
includes changing the size of an array. An array is a collection of items stored at contiguous
memory locations.
As can be seen, the length (size) of the array above is 9. But what if there is a requirement to
change this length (size)? For example,
• If there is a situation where only 5 elements are needed to be entered in this array. In
this case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9 elements with all 9 indices filled.
But there is a need to enter 3 more elements in this array. In this case, 3 indices more are
required. So the length (size) of the array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by
C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming.
They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.
C malloc() method
Syntax of malloc() in C
Example:
Ptr=(int*) malloc(100*szeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h>
int main()
int* ptr;
int n, i;
scanf("%d",&n);
if (ptr == NULL) {
exit(0);
else {
ptr[i] = i + 1;
return 0;
Output
C calloc() method
This statement allocates contiguous space in memory for 25 elements each with the size of
the float.
If space is insufficient, allocation fails and returns a NULL pointer.
Example of calloc() 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
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]);
}
}
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
C free method
“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);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
C realloc() method
“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.
re-allocation 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'.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
free(ptr);
}
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
PART-A
PART-B
1. Explain the concept of Structure with relevant example program.
2. Describe Array of Structures with suitable example.
3. Define a structure called Student that contains the name, regno, marks of five subjects
and percentage. Write a program to read the details of name, regno and marks of five
subjects for 30 students, calculate the percentage and display the name, regno, marks
of the subjects and percentage of each student. (Use Array of Structure concept)
4. Write a C program to define a Structure ‘Employee’ that reads and display the details
such as empno, empname, department name and salary. The structure has to store 100
employees in an organization (Use Array of Structure concept)
5. Explain in detail about Structure within Structure (Nested Structure) with relevant
example program.
6. Discuss Array within Structure with suitable example.
7. Explain how to pass structure as arguments to function with example.
8. Describe the concept of Type defining structures with an example.
9. Explain about Pointer in C? With Suitable example.
10. Explain about arithmetic Pointer in C with suitable example.
11. Illustrate about following term
a. Double Pointer
b. Dereferencing operator in C
12. Write a program to access Pointer variable in structure.
13. How to access array element using Pointer in C.
14. Write a program for accessing structure member using Pointer?
15. Explain about Dynamic Memory Allocation in C.