Module 4
• Scope,Lifetime,Visibility—Assignment topic
Structure in C
• Structures (also called structs) are a way to group
several related variables into one place.
• Each variable in the structure is known as a member of
the structure.
• Unlike an array, a structure can contain many different
data types (int, float, char, etc.).
• Syntax of Structure Declaration
struct [structure tag]{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
• Create a Structure
struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
Structure Variable Declaration
• To declare a structure variable, write the structure
name along with the "struct" keyword followed by the
name of the structure variable.
• Example:struct myStructure s1;
• Structure variables There are three methods of declaring structure variables, which are as follows
• −First method
struct book
{ int pages;
char author[30];
float price;}b;
• Second method
struct{ int pages; char author[30]; float price;}b;
• Third method
struct book
{ int pages; char author[30]; float price;};
struct book b;
• Exmple
• struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
• To access members of a structure, use the dot syntax (.)
• Example
• // Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
[Link] = 13;
[Link] = 'B';
// Print values
printf("My number: %d\n", [Link]);
printf("My letter: %c\n", [Link]);
return 0;
}
• Real time 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 %d\n", [Link], [Link], [Link]);
printf("%s %s %d\n", [Link], [Link], [Link]);
printf("%s %s %d\n", [Link], [Link], [Link]);
return 0;
}
Comparison of two structure
• Example
• Following is the C program for the comparison of structure variables − struct class
{ int number;
char name[20];
float marks;};
main()
{ int x;
struct class student1 = {001,"Hari",172.50};
struct class student2 = {002,"Bobby", 167.00};
struct class student3;
student3 = student2;
x = (([Link] == [Link]) && ([Link] == [Link])) ? 1 : 0;
if(x == 1)
{ printf("student2 and student3 are same");
printf("%d %s %f", [Link], [Link], [Link]); }
else
printf("student2 and student3 are different");}
Array of Structures in C
• An array of structures is simply an array where each element
is a structure. It allows you to store several structures of the
same type in a single array.
• Array of Structure Declaration
• struct struct_name arr_name [size];
Example
struct A {
int var;
char c;
};
int main() {
// Declaration and initialization using nested
// initializer list
struct A arr1[2] = { {1, 'a'}, {2, 'b'} };
// Declaration and initialization using non-nested
// initializer list
struct A arr2[2] = { 10, 'A', 20, 'B' };
// Designated initialization
struct A arr3[2] = { {.c = 'A', .var = 10},
{.var = 2, .c = 'b'} };
Array within Structure in C
• An array can be declared inside a structure as a member when
we need to store multiple members of the same type
• Syntax to Declare Array Within Structure
struct StructureName {
// Other members
dataType arrayName[arraySize];
}
int main()
• C program to demonstrate the array within {
structures // defining structure of type Employee
struct Employee emp;
#include <string.h> // adding data
[Link] = 1;
#include <stdio.h>
strcpy([Link], "Rohit");
// Defining array within structure int week;
struct Employee { for (week = 0; week < 7; week++) {
// character array to store name of the employee int attendence;
[Link][week] = week;
char Name[20];
}
int employeeID; printf("\n");
int WeekAttendence[7]; // printing the data
}; printf("Emplyee ID: %d - Employee Name: %s\n",
[Link], [Link]);
printf("Attendence\n");
for (week = 0; week < 7; week++) {
printf("%d ", [Link][week]);
}
printf("\n");
return 0;
}
Nested Structure in C
• A nested structure in C is a structure within structure. One structure can be declared inside
another structure in the same way structure members are declared inside a structure.
struct name_1
{
member1;
member2;
.
.
membern;
• struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;
• Example • struct Employee
• // C program to implement • {
• int employee_id;
• // the above approach • char name[20];
• #include <stdio.h> • int salary;
•
• // This line will cause error because
• // Declaration of the outer • // datatype struct Employee is present ,
• // but Structure variable is missing.
• // structure
• };
• struct Organisation • };
• {
• // Driver code
• char organisation_name[20]; • int main()
• char org_number[20]; • {
• // Structure variable of organisation
• • struct Organisation org;
• // Declaration of the employee • printf("%ld", sizeof(org));
• }
• // structure
Structures and Functions in C
• Just as we can pass arguments of primary data types, a variable of
struct data type can also be passed to a function. You can also pass
structures using call by value and call by reference methods. A
function in C may also return a struct data type.
#include <stdio.h>
struct rectangle { struct rectangle area(float x, float y){
float len, brd;
double area; double area = (double)(x*y);
}; struct rectangle r = {x, y, area};
struct rectangle area(float x, float y);
int main(){ return r;
struct rectangle r; }
float x, y;
x = 10.5; y = 20.5;
r = area(x, y);
printf("Length: %f \n Breadth: %f \n Area: %lf\n", [Link],
[Link], [Link]);
return 0;
}
Union
• In C, union is a user-defined data type 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 point in time.
union A { • // Storing an integer
int i; • a.i = 10;
float f; • printf("data.i = %d", a.i);
char s[20];
}; • // Storing a float
int main() { • a.f = 220.5;
union A a; • printf("data.f = %.2f", a.f);
• // Storing a string
• strcpy(a.s, "GfG");
• printf("data.s = %s", a.s);
C Union Declaration
• union name {
type1 member1;
type2 member2;
.
.
};
Creating Union Variable
• union name{
type member1;
type member2;
…
} var1, var2, …;
• union name var1, var2, var3…;
Access Union Members
• var1.member1;
Initialize Union
• var1.member1 = val;
Size of Union
• Only one member can contain some value at a given instance of time.
• The size of the union will always be equal to the size of the largest
member of the union
union A{ int main() {
int x;
char y; // Finding size using sizeof()
}; operator
printf("Sizeof A: %ld\n",
sizeof(union A));
union B{ printf("Sizeof B: %ld\n",
int arr[10]; sizeof(union B));
char y;
}; return 0;
}
Example
#include <stdio.h> int main(){
#include <string.h> union Data data;
union Data{ data.i = 10;
int i; data.f = 220.5;
float f; strcpy([Link], "C Programming");
char str[20];
}; printf("data.i: %d \n", data.i);
printf("data.f: %f \n", data.f);
printf("[Link]: %s \n", [Link]);
return 0;
}
output
• data.i: 1917853763
• data.f:
41223605803277948604527599
94368.000000
• [Link]: C Programming
Structure Union
• The size of the structure is equal
• The size of the union is the size
to or greater than the total size
of its largest member.
of all of its members.
• The structure can contain data
• Only one member can contain
in multiple members at the
data at the same time.
same time.
• It is declared using the struct • It is declared using the union
keyword. keyword.
Pointers
• A pointer is a variable that stores the memory address of
another variable.
• Instead of holding a direct value, it holds the address where
the value is stored in memory. There are 2 important
operators that we will use in pointers concepts i.e.
• Dereferencing operator(*) used to declare pointer variable and
access the value stored in the address.
• Address operator(&) used to returns the address of a variable
or to access the address of a variable to a pointer.
EXAMPLE
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name
ptr, that stores the address of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the pointer
(0x7ffe5367e044)
printf("%p\n", ptr);
• Pointer Declaration
• type *var-name;
• Ex:
• int *ip; /* pointer to an integer */
• double *dp; /* pointer to a double */
• float *fp; /* pointer to a float */
• char *ch /* pointer to a character */
• 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.
• pointer_variable = &variable;
• Ex:
int x = 10;
int *ptr = &x;
Accessing a variable through address and
through pointer
• To access a variable through its address and a pointer, you use the address-of operator (&) to get the
memory address, and the dereference operator (*) to access the value at that address.
#include <stdio.h>
int main() {
int x = 10;
int *ptr;
// Get the address of x
ptr = &x;
// Access the value of x through the pointer
printf("Value of x: %d\n", *ptr); // Output: Value of x: 10
printf("Address of x: %p\n", ptr); // Output: Address of x: (some memory address)
printf("Address of x (using &): %p\n", &x); // Output: Address of x (using &): (some memory address)
return 0;
}
Pointer Expressions in C
• Examples:
int *ptr_a, *ptr_b;
// Initialization of pointers
ptr_a = &a;
ptr_b = &b;
// Performing arithmetic Operations
// on pointers
add = *ptr_a + *ptr_b;
sub = *ptr_a - *ptr_b;
mul = *ptr_a * *ptr_b;
div = *ptr_a / *ptr_b;
mod = *ptr_a % *ptr_b;
Relational Operators
Relational operations are often used to compare • if (*ptr_a < *ptr_b) {
the values of the variable based on which we
can take decisions • printf(
int main() • %d is less than %d, *ptr_a, *ptr_b);
{ // Initializing integer variables • } // Greater than operator
int a = 20, b = 10; • if (*ptr_a > *ptr_b) {
// Declaring pointer variables • printf(
int* ptr_a; • “%d is greater than %d”, *ptr_a, *ptr_b); }
int* ptr_b; • // Equal to
// Initializing pointer variables • if (*ptr_a == *ptr_b) {
ptr_a = &a; • printf(
ptr_b = &b; • %d is equal to %d, *ptr_a, *ptr_b);
// Performing relational operations • }
// less than operator
Assignment Operators
• Assignment operators are used to assign values to the identifiers.
int a = 30;
// Declaring pointer variable
int* ptr_a;
// Initializing pointer using
// assignment operator
ptr_a = &a;
// Changing the variable's value using
// assignment operator
*ptr_a = 50;
Conditional Operators
• Syntax:-expression1 ? expression2 : expression3;
• Example:- c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2;
Unary Operators
• (*ptr1)++ // Unary increment operation
(*ptr_a)++;
• (*ptr1)—
// Value of a after increment
• Example printf(
int a = 34; “After increment a = %d”,*ptr_a);
// Declaring pointer variable // Value before decrement
int* ptr_a; printf(“Decrement:”);
// Initializing pointer variable printf(
ptr_a = &a; “Before decrement a = %d”, *ptr_a);
// Value of a before increment // unary decrement operation
printf( (*ptr_a)--;
“After increment a = %d”,*ptr_a); // Value after decrement
printf(“After decrement a=%d”, *ptr_a);
Bitwise Operators
• Binary operators are also known • Example
as bitwise operators. It is used to • *ptr1 & *ptr2
manipulate data at bit level. • *ptr1 | *ptr2
Bitwise operators can’t be used • *ptr1 ^ *ptr2
for float and double datatype.
Pointer increment and scale factor
• Increment: It is a condition that also comes under int a = 22;
addition. When a pointer is incremented, it
actually increments by the number equal to the int *p = &a;
size of the data type for which it is a pointer. printf("p = %u\n", p); // p = 6422288
• If an integer pointer that stores address 1000 is p++;
incremented, then it will increment by 4(size of an
int), and the new address will point to 1004. While printf("p++ = %u\n", p); //p++=6422292,4 bytes
if a float type pointer is incremented then it will
increment by 4(size of a float) and the new address float b = 22.22;
will be 1004. float *q = &b;
• Example: printf("q = %u\n", q); //q = 6422284
char c = 'a'; q++;
char *r = &c; printf("q++ = %u\n", q); //q++ = 6422288,4 byte
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1bytes
• Pointer Increment: • If you have an int* pointer
• When you increment a pointer (pointing to an integer),
(e.g., p++), you're not just incrementing it moves the
adding 1 to the address; you're pointer to the next integer
adding a value that depends on location, which is likely 4 bytes
the size of the data type the away (assuming integers are 4
pointer holds. bytes).
• Scale Factor: • The amount by which a pointer
increments is determined by the
• The scale factor is the size of the scale factor of the data type it
data type in bytes. For example: points to.
Pointers and Arrays
• Syntax:pointer_type *array_name [array_size]; • Output
• Example: • Value of var1: 10 Address: 0x7fff1ac82484
int main() • Value of var2: 20 Address: 0x7fff1ac82488
{ // declaring some temp variables • Value of var3: 30 Address: 0x7fff1ac8248c
int var1 = 10;
int var2 = 20;
int var3 = 30;
// array of pointers to integers
int* ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1,
*ptr_arr[i], ptr_arr[i]);
}
return 0;}
Pointer and function
• A variable that stores the address of a function is called a function pointer or a pointer to a function
• Declaration Syntax
function_return_type(*Pointer_name)(function argument list)
Example:#include <stdio.h>
// Defining a function
void hello() {
printf("Hello World"); }
// The main code
int main() {
// Declaring a function pointer
void (*ptr)() = &hello;
// Calling function using the function poiter
(*ptr)();
return 0;}
O/P:
Hello world
Pointer and Structure
• A structure pointer is a pointer variable that stores the address of a
structure. It allows the programmer to manipulate the structure and its
members directly by referencing their memory location rather than passing
the structure itself
• Syntax: struct struct_name *ptr_name;
Here, struct_name is the name of the structure, and ptr_name is the
name of the pointer variable.
• There are two ways to access the members of the structure with the help
of a structure pointer:
• Differencing and Using (.) Dot Operator.
• Using ( -> ) Arrow operator.
EX:
struct A {
int var;};
int main() {
struct A a = {30};
// Creating a pointer to the structure
struct A *ptr;
// Assigning the address of person1 to the pointer
ptr = &a;
// Accessing structure members using the pointer
printf("%d", ptr->var);
return 0;
}
O/P
30
Memory management
• In C, a variable defined in a function is stored in the stack memory.
The requirement of this memory is that it needs to know the size of
the data to memory at compile time (before the program runs). Also,
once defined, we can neither change the size nor completely delete
the memory.
• To resolve this, C provides a feature called Dynamic Memory
Allocation. It allows you to allocate memory at runtime, giving your
program the ability to handle data of varying sizes. Dynamic resources
are stored in the heap memory instead of the stack.
• This feature is useful in a variety of situations. For example, changing
the size of an array according to our requirement.
• As we know, the size of an array in C is fixed and should be
known at compile time. There can be two problems:
• The size of the array is not sufficient to store all the elements.
To resolve this, one might set the size to store the maximum
theoretically possible elements. This creates another problem.
• This size of the array is much more than what is required to store the
elements. This leads to the wastage of memory.
• This is where the dynamic memory allocation comes in. The size of
the array can be increased if more elements are to be inserted and
decreased of less elements are inserted. Moreover, there is no need
to estimate the max possible size. The size can be decided at runtime
according to the requirement.
• Dynamic Memory Allocation in C
• Dynamic memory allocation is possible in C by using 4 library
functions provided by <stdlib.h> library:
malloc()
calloc()
free()
realloc()
• malloc()
The malloc() (stands for memory allocation) function is used to allocate
a single block of contiguous memory on the heap at runtime. The
memory allocated by malloc() is uninitialized, meaning it contains
garbage values
• Syntax:malloc(size);
• Assume that we want to create an array to store 5 integers. Since the
size of int is 4 bytes, we need 5 * 4 bytes = 20 bytes of memory. This
can be done as shown:
• int *ptr = (int *)malloc(20);
• calloc()
The calloc() (stands for contiguous allocation) function is similar to
malloc(), but it initializes the allocated memory to zero. It is used when
you need memory with default zero values.
• Syntax:calloc(n, size);
• Example:int *ptr = (int *)calloc(sizeof(int), 5);
• free()
• The memory allocated using functions malloc() and calloc() is not de-
allocated on their own. The free() function is used to release
dynamically allocated memory back to the operating system. It is
essential to free memory that is no longer needed to avoid memory
leaks.
• Syntax: free(ptr);
• realloc()
• realloc() function is used to resize a previously allocated memory
block. It allows you to change the size of an existing memory
allocation without needing to free the old memory and allocate a new
block.
• Syntax: realloc(ptr, new_size);
• Ex:ptr = (int *)realloc(ptr, 10 * sizeof(int));
END