0% found this document useful (0 votes)
7 views39 pages

Unit 3

The document covers various advanced topics in C programming, including derived types such as structures, nested structures, unions, and typedefs, as well as pointers and dynamic memory management. It explains the concepts and provides code examples for each topic, highlighting the differences between structures and unions, the use of pointers, and memory allocation functions like malloc, calloc, and realloc. Additionally, it discusses command line arguments and their syntax for passing parameters to programs.

Uploaded by

danivlogs7777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views39 pages

Unit 3

The document covers various advanced topics in C programming, including derived types such as structures, nested structures, unions, and typedefs, as well as pointers and dynamic memory management. It explains the concepts and provides code examples for each topic, highlighting the differences between structures and unions, the use of pointers, and memory allocation functions like malloc, calloc, and realloc. Additionally, it discusses command line arguments and their syntax for passing parameters to programs.

Uploaded by

danivlogs7777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Unit 3

Derived types: structures, nested structures,


self-referential structures, unions, typedef,
pointers-dynamic memory managements
functions, command line arguments
Structures
• Structure is a user-defined data type that
combines logically related data items of
different data types together.
• Structure stores the different types of
elements i.e heterogeneous elements.
#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[60];
}s1; //declaring s1 variable for structure
void main( )
{ //store first employee information
s1.rollno=1;
printf( "Rollno : %d\n", s1.rollno);
s1.name = “Arjun”
printf( "Name : %s\n", s1.name);
}
Nested structures
The structure can be nested in the following
different ways:

• By separate nested structure


• By embedded nested structure.
By separate nested structure
#include <stdio.h> struct Organisation
#include <string.h> {
char
struct Employee organisation_name[20];
{
int employee_id; char org_number[20];
char name[20]; struct Employee emp;
int salary; };
};
int main()
{
struct Organisation org;
printf("The size of structure organisation : %ld\n",
sizeof(org));
org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "VelsUniv");
strcpy(org.org_number, "VELS123768");
printf("Organisation Name : %s\n", org.organisation_name);
printf("Organisation Number : %s\n", org.org_number);
printf("Employee id : %d\n", org.emp.employee_id);
printf("Employee name : %s\n", org.emp.name);
printf("Employee Salary : %d\n", org.emp.salary);
}
2. By Embedded nested structure
Note:
Whenever an embedded nested structure is
created, the variable declaration is compulsory
at the end of the inner structure, which acts as a
member of the outer structure. It is compulsory
that the structure variable is created at the end
of the inner structure.
/#include <stdio.h>
#include <string.h>

struct Organisation
{
char organisation_name[20];
char org_number[20];

struct Employee
{
int employee_id;
char name[20];
int salary;
} emp;
};
int main()
{
struct Organisation org;
printf("The size of structure organisation : %ld\n", sizeof(org));

org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "VelsUniv");
strcpy(org.org_number, "VISTAS123768");
printf("Organisation Name : %s\n", org.organisation_name);
printf("Organisation Number : %s\n", org.org_number);
printf("Employee id : %d\n", org.emp.employee_id);
printf("Employee name : %s\n", org.emp.name);
printf("Employee Salary : %d\n", org.emp.salary);
}
Pointers
Pointers are one of the most important and
powerful features of the C programming
language. They allow us to manipulate memory
directly, which can be very useful in many
programming scenarios.

In C, a pointer is simply a variable that holds a


memory address. We can think of it as a way to
refer to a specific location in memory.
Declaration of pointer:
int *p; (or) int* p;
Both of these declarations are equivalent and they
declare a pointer variable named "p" that can hold
the memory address of an integer.

However, it's important to note that if you declare


multiple variables in a single statement, you need to
include the asterisk before each variable name to
indicate that they are all pointers. For example:
int *p, *q, *r;
This declares three pointer variables named "p", "q",
and "r" that can hold the memory address of an
integer.
Initializing a pointer
int x = 42;
int *p = &x;

This sets the value of p to be the memory


address of x.
Dereferencing the pointer
Once we have a pointer that points to a specific
memory location, we can access or modify the value
stored at that location by dereferencing the pointer.

To dereference a pointer, we use the asterisk * symbol


again, but this time in front of the pointer variable
itself. For example, to print the value of the integer that
p points to, we would write:

printf("%d\n", *p);
#include <stdio.h>

int main() {
int a= 44;
int *b = &a;

printf("%d" , *b);
}
Pointer to pointer
A pointer can also point to another pointer variable. This is
known as a "pointer to a pointer". We declare a pointer to a
pointer by using two asterisks **. For example:

int x = 42;
int *p = &x;
int **q = &p;

Here, q is a pointer to a pointer. It points to the address of the


p variable, which in turn points to the address of the x
variable
Self-referential structures
• A self-referential structure is a structure that contains
a pointer to a variable of the same type.
• This allows the structure to refer to itself, creating a
linked data structure.
• Self-referential structures are a powerful tool for
creating complex data structures and are commonly
used in algorithms such as trees, graphs, and linked
lists.
• Self-referential structures, typically implemented
using pointers.
• There are two types: Linear and Non-linear
Union
• A union is a user-defined type similar
to structure except for one key difference.
• Structures allocate enough space to store all
their members, whereas unions can only hold
one member value at a time.
• Example:

union car
{
char name[50];
int price;
} car1;
Union vs Structure
#include <stdio.h>
union unionJob
{
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40

Why this difference in the size of union and structure variables?


Here, the size of sJob is 40 bytes because
the size of name[32] is 32 bytes
the size of salary is 4 bytes
the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes.


It's because the size of a union variable will always be the size of
its largest element. In the above example, the size of its
largest element, (name[32]), is 32 bytes.
With a union, all members share the same memory.
#include <stdio.h> Salary = 0.0
union Job Number of workers = 100

{
float salary;
int workerNo;
} j;
int main()
{
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
Typedef
• The typedef is a keyword used in C
programming to provide some meaningful
names to the already existing variable in the C
program.
• we can replace the name of the existing data
type with the name which you have provided.
• It works similarly when we define aliases for
the commands.
Typedef
Syntax:
typedef <existing_name> <alias_name>

Example:
typedef long int lint;
Typedef example
#include <stdio.h>
struct student
int main()
{
{ char name[20];
typedef long int lint; int age;
lint i,j; };
i=100000; typedef struct student stud;
j=200000;
printf("Value of i is :%ld",i); stud s1, s2;
printf("\nValue of j is :%ld",j);
return 0;
}
Dynamic memory management functions
• Memory allocation is the act of allocating blocks
of physical memory to a particular program for it
to store data during execution.
• Allocation can take two forms: static and dynamic.
• Static memory allocation is when a certain amount
of memory has been preallocated for a program
and cannot be changed during runtime.
• Conversely, dynamic memory allocation is when
the amount of allocated memory can be adjusted
during runtime as needed by the program.
Dynamic memory allocation in C
C provides several functions in stdlib library for
dynamic memory allocation. <stdlib.h>
• malloc() allocates single block of requested
memory.
• calloc() allocates multiple block of requested
memory.
• realloc() reallocates the memory occupied by
malloc() or calloc() functions.
• free() frees the dynamically allocated
memory.
malloc()
General Syntax:
(cast-data-type *)malloc(size-in-bytes);

Example Syntax:
int *ptr = (int *)malloc(sizeof(int));

sizeof() automatically takes care of the type of compiler and


operating system that can cause changes in sizes of
different data types on different compilers and operating
systems, so it is recommended to use sizeof() function in
Dynamic Memory Allocation in C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *var = (int*) malloc(sizeof(int));
printf("Garbage value at var: %d\n",*var);
*var = 5;
printf("Value at var is: %d\n",*var);
return 0;
}
free()
• free() function to deallocate the memory.
• Memory allocated by the malloc()/calloc()
doesn’t deallocate when the variable goes
out of scope, it deallocates when the program
ends or uses the free() function.
• Memory leaks occur when new memory is
allocated dynamically and never deallocated
calloc()
Syntax:
pointer= (cast_type *) calloc (number_of_block,
size_of_block);
Example:
//character array of 5 elements
char *str = (char *)calloc(5, sizeof(char));
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
char *str = (char *)calloc(n,
sizeof(char));
if (str == NULL)
printf("Memory Error!\n");
else
{
for (int i = 0; i < n; i++)
{
char ch;
scanf("%c", &ch);
*(str + i) = ch;
}
}
for (int i = 0; i < n; i++)
printf("%c", *(str + i));
return 0;
}
realloc()
realloc() is also a method that is generally used
to reallocate a memory block, here re-allocate
means to increase or decrease the size of a
memory block previously allocated using
malloc() or calloc() methods.
command line arguments

Command line argument is a parameter


supplied to the program when it is invoked or
run.
we can enter values from the command line at
the time of execution.
Command line arguments are passed to the
main() method.
Syntax:
int main(int argc, char *argv[])
argc (ARGument Count) denotes the number of
arguments to be passed and
argv [ ] (ARGument Vector) denotes a pointer
array pointing to every argument that has been
passed to your program.
#include <stdio.h>

int main( int argc, char *argv [] )


{
printf(" \n Name of my Program %s \t", argv[0]);

if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy