Structures allow grouping of related data types together under one name. Structures can contain members of different data types. Structures are defined using the struct keyword and variables of structure types can be declared. Members of a structure are accessed using the dot (.) operator. Pointers to structures allow dynamic allocation of structures and accessing structure members using the arrow (->) operator. Arrays of structures help organize collections of related data records. Structures and pointers are useful for implementing linked lists and trees.
Structures in Functions | Pointers to structures | Accessing structure members | Using pointer as a function argument | Array of structures | Self referential structures
A Structure is a convenient tool for handling a group of logically related data items. A collection of one or more variables, typically of different types, grouped together under a single name is known as structure.
Structures in Functions | Pointers to structures | Accessing structure members | Using pointer as a function argument | Array of structures | Self referential structures
A Structure is a convenient tool for handling a group of logically related data items. A collection of one or more variables, typically of different types, grouped together under a single name is known as structure.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
ARRAYS
TYPES OF ARRAYS
MULTIDIMENSIONAL ARRAYS
CHARACTER HANDLING IN C
STRING HANDLING IN C
QUIZ SET 2
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
ARRAYS
TYPES OF ARRAYS
MULTIDIMENSIONAL ARRAYS
CHARACTER HANDLING IN C
STRING HANDLING IN C
QUIZ SET 2
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
2. Heterogeneous Structures
Collection of values of possibly different types.
Name the collection.
Name the components.
Example : Student record
Singhal
name "V Singhal"
rollno "00CS1001"
classtest 14
midterm 78
final 73
grade ‘B
3. Structure : terminology
A struct is a group of items (variables) which
may be of different types.
Each item is identified by its own identifier,
each of which is known as a member or field
of the structure.
A struct is sometimes called a record or
structure.
Structs are the basis of classes in C++ and
Java.
4. Structure declaration
struct {
char first[10];
char midinit;
char last[20];
} sname, ename;
This declaration creates
two structure variables,
sname and ename, each
of which contains 3
members.
We can use
sname.first,
ename.midinit,
etc.
5. Members
To access the members of a structure,
we use the member access operator “.”.
strcpy (sname.first, “Sudeshna”);
sname.midinit = ‘K’;
strcpy (sname.last, “Sarkar”) ;
6. Tagged structure
struct nametype {
char first[10];
char midinit;
char last[20];
};
struct nametype sname,
ename;
typedef struct nametype NTYPE;
NTYPE aname, bname;
This definition creates
a structure tag nametype
containing 3 members:
first, midinit, last.
Variables may be declared
of type struct <tagname>.
typedef is normally used
to give names to a
struct type.
8. Another example
#define MAX_NAME 40
typedef struct {
char name[MAX_NAME+1];
char rollno[10];
int classtest;
int midterm;
int final;
char grade;
} StudentRecord;
Defines a new data type called StudentRecord. Does
not declare a variable.
9. Declaring struct variables
/* typedef structs go at top of program */
. . .
int .....
float ....
StudentRecord s1;
StudentRecord singhal ;
/* StudentRecord is a type; s1 and singhal are variables*/
struct nametype aname;
/* struct nametype is a type; aname is a variable */
10. Things you can and can't do
You can
Use = to assign whole struct variables
You can
Have a struct as a function return type
You cannot
Use == to directly compare struct variables;
can compare fields directly
You cannot
Directly scanf or printf structs; can read
fields one by one.
11. Struct initializers
/* typedef structs go on top */
StudentRecord s1 = {"V Singhal", "00CS1002", 15,
78, 73, 'B'};
Using components of struct
variables
s1.classtest = 46;
s1.midterm = 78;
scanf ("%d", &s1.rollno) ;
13. Within a given structure, the member names
must be unique.
However, members in different structures
may have the same name.
A member is always accessed through a
structure identifier.
struct fruit {
char name[20];
int calories;
};
struct vegetable {
char name[30];
int calories;
};
struct fruit mango;
struct vegetable potato;
It is clear that we can
access mango.calories and
potato.calories without
any ambiguity.
14. Complicated structures
A member of a structure can be an array or
another structure.
struct grocerylist {
struct fruit flist[10];
struct vegetable vlist[20];
} ;
You can have an array of structures.
struct card {
int pips;
char suit;
} deck[52] ;
15. A function using struct array
int fail (StudentRecord slist []) {
int i, cnt=0;
for (i=0; i<CLASS_SIZE; i++)
cnt += slist[i].grade == ‘F’;
return cnt;
}
16. Using structures with functions
Structures can be passed as arguments to functions.
Structures can be returned from functions.
Call by value is used if a structure is a function
parameter, meaning that a local copy is made for use
in the body of the function. If a member of the
structure is an array, then the array gets copied as
well.
If the structure is large, passing the structure as an
argument can be relatively inefficient. An address of
th structure may be used as the parameter.
17. Union
A union is like a structure, except that the members
of a union share the same space in memory.
union int_or_float {
int i;
float f;
};
It is the programmer’s responsibility to know which
representation is currently stored in a union
variable.
18. Arrays of Structures
A struct represents a single record.
Typically structs are used to deal with
collections of such records
Examples : student records, employee
records, book records, ...
In each case we will hav multiple instances of
the struct type.
Arrays of structs are the natural way to do this.
19. Arrays of structs : declaration & use
Each declaration below declares an array, where
each array element is a structure:
point corner_points[10] ;
StudentRecord btech01[MAXS] ;
We access a field of a struct in an array by specifying
the array element and then the field :
btech01[i].name
corner_points[4].x
20. Naming in struct Arrays
point pentagon[5];
x
y
x
y
x
y
x
y
x
y
pentagon : an array of points
pentagon[1] : a point structure
pentagon[4].x : a double
21. Using Arrays of structs
StudentRecord class[MAXS];
...
for (i=0; i<nstudents; i++) {
scanf (“%d%d”, &class[i].midterm,
&class[i].final);
class[i].grade =
(double)(class[i].midterm+class[i].final)/50.0;
}
22. struct Array elements as parameters
void draw_line (point p1, point p2) { ... }
...
point pentagon[5];
...
for (i=0;i<4;i++)
draw_line (pentagon[i], pentagon[i+1]);
draw_line (pentagon[4], pentagon[0]);
23. structs as Parameters
A single struct is passed by value.
all of its components are copied from the
argument (actual parameter) to initialize
the (formal) parameter.
point set_midpt (point a, point b) { ... }
int main (void) {
point p1, p2, m;
...
m = set_midpt(p1, p2);
}
24. Passing Arrays of structs
An array of structs is an array.
When any array is an argument (actual parameter), it
is passed by reference, not copied [As for any array]
The parameter is an alias of the actual array
argument.
int avg (StudentRec class[MAX]) { ... }
int main (void) {
StudentRec bt01[MAX];
int average;
...
average = avg_midpt(bt01) ;
}
26. Basic Idea
Many a time we face situations where data is
dynamic in nature.
Amount of data cannot be predicted
beforehand.
Number of data item keeps changing
during program execution.
Such situations can be handled more easily
and effectively using dynamic memory
management techniques.
27. C language requires the number of
elements in an array to be specified at
compile time.
Often leads to wastage or memory space
or program failure.
Dynamic Memory Allocation
Memory space required can be specified
at the time of execution.
C supports allocating and freeing memory
dynamically using library routines.
28. Memory Allocation Process in
C
Local variables
Free memory
Global variables
Instructions
Permanent
storage area
Stack
Heap
29. The program instructions and the global
variables are stored in a region known
as permanent storage area.
The local variables are stored in another
area called stack.
The memory space between these two
areas is available for dynamic allocation
during execution of the program.
This free region is called the heap.
The size of the heap keeps changing
30. 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.
31. Dynamic Memory Allocation
used to dynamically create space for
arrays, structures, etc.
int main () {
int *a ;
int n;
....
a = (int *) calloc (n, sizeof(int));
....
}
a = malloc (n*sizeof(int));
32. Space that has been dynamically
allocated with either calloc() or malloc()
does not get returned to the function
upon function exit.
The programmer must use free()
explicitly to return the space.
ptr = malloc (...) ;
free (ptr) ;
33. void read_array (int *a, int n) ;
int sum_array (int *a, int n) ;
void wrt_array (int *a, int n) ;
int main () {
int *a, n;
printf (“Input n: “) ;
scanf (“%d”, &n) ;
a = calloc (n, sizeof (int)) ;
read_array (a, n) ;
wrt_array (a, n) ;
printf (“Sum = %dn”, sum_array(a, n);
}
34. void read_array (int *a, int n) {
int i;
for (i=0; i<n; i++)
scanf (“%d”, &a[i]) ;
}
void sum_array (int *a, int n) {
int i, sum=0;
for (i=0; i<n; i++)
sum += a[i] ;
return sum;
}
void wrt_array (int *a, int n) {
int i;
........
}
35. Arrays of Pointers
Array elements can be of any type
array of structures
array of pointers
36. int main (void) {
char word[MAXWORD];
char * w[N]; /* an array of pointers */
int i, n; /* n: no of words to sort */
for (i=0; scanf(“%s”, word) == 1); ++i) {
w[i] = calloc (strlen(word)+1, sizeof(char));
if (w[i] == NULL) exit(0);
strcpy (w[i], word) ;
}
n = i;
sortwords (w, n) ;
wrt_words (w, n);
return 0;
}
37. w
0
1
2
3
17
Input : A is for apple or alphabet pie which
all get a slice of come taste it and try
A 0
i s 0
f o r 0
a p p l e 0
t r y 0
38. void sort_words (char *w[], int n) {
int i, j;
for (i=0; i<n; ++i)
for (j=i+1; j<n; ++j)
if (strcmp(w[i], w[j]) > 0)
swap (&w[i], &w[j]) ;
}
void swap (char **p, char **q) {
char *tmp ;
tmp = *p;
*p = *q;
*q = tmp;
}
42. Pointers and Structures
You may recall that the name of an array stands
for the address of its zero-th element.
Also true for the names of arrays of structure
variables.
Consider the declaration:
struct stud {
int roll;
char dept_code[25];
float cgpa;
} class[100], *ptr ;
43. The name class represents the address of the
zero-th element of the structure array.
ptr is a pointer to data objects of the type
struct stud.
The assignment
ptr = class ;
will assign the address of class[0] to ptr.
When the pointer ptr is incremented by one
(ptr++) :
The value of ptr is actually increased by
sizeof(stud).
It is made to point to the next record.
44. Once ptr points to a structure variable,
the members can be accessed as:
ptr –> roll ;
ptr –> dept_code ;
ptr –> cgpa ;
The symbol “–>” is called the arrow
operator.
45. Warning
When using structure pointers, we should take
care of operator precedence.
Member operator “.” has higher precedence than “*”.
ptr –> roll and (*ptr).roll mean the same thing.
*ptr.roll will lead to error.
The operator “–>” enjoys the highest priority
among operators.
++ptr –> roll will increment roll, not ptr.
(++ptr) –> roll will do the intended thing.
46. Program to add two complex
numbers using pointers
typedef struct {
float re;
float im;
} complex;
main() {
complex a, b, c;
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
add (&a, &b, &c) ;
printf (“n %f %f”, c,re, c.im);
}
49. Dynamic allocation: review
Variables in C are allocated in one of 3 spots:
the run-time stack : variables declared local to
functions are allocated during execution
the global data section : Global variables are
allocated here and are accessible by all parts of a
program.
the heap : Dynamically allocated data items
malloc, calloc, realloc manage the heap region of the
mmory. If the allocation is not successful a NULL value
is returned.
50. Bad Pointers
When a pointer is first allocated, it does not have a
pointee.
The pointer is uninitialized or bad.
A dereference operation on a bad pointer is a serious
runtime error.
Each pointer must be assigned a pointee before it can
support dereference operations.
int * numPtr;
Every pointer starts out with a bad value. Correct code
overwrites the bad value.
51. Example pointer code.
int * numPtr;
int num = 42;
numPtr = #
*numPtr = 73;
numPtr = malloc (sizeof (int));
*numPtr = 73;
52. int a=1, b=2, c=3;
int *p, *q;
1
a
3
c
2
b
xxx
xxx
p
q
55. Bad pointer Example
void BadPointer () {
int *p;
*p = 42;
}
int * Bad2 () {
int num, *p;
num = 42;
p = #
return p;
}
x x x
p
X
56. A function call malloc(size) allocates a block of mrmory
in the heap and returns a pointer to the new block.
size is the integer size of the block in bytes. Heap
memory is not deallocated when the creating function
exits.
malloc generates a generic pointer to a generic data
item (void *) or NULL if it cannot fulfill the request.
Type cast the pointer returned by malloc to the type of
variable we are assigning it to.
free : takes as its parameter a pointer to an allocated
region and de-allocates memory space.
57. Dynamic memory allocation: review
typedef struct {
int hiTemp;
int loTemp;
double precip;
} WeatherData;
main () {
int numdays;
WeatherData * days;
scanf (“%d”, &numdays) ;
days=(WeatherData *)malloc (sizeof(WeatherData)*numdays);
if (days == NULL) printf (“Insufficient memory”);
...
free (days) ;
}
58. Self-referential structures
Dynamic data structures : Structures with
pointer members that refer to the same
structure.
Arrays and other simple variables are
allocated at block entry.
But dynamic data structures require
storage management routine to explicitly
obtain and release memory.
59. Self-referential structures
struct list {
int data ;
struct list * next ;
} ;
The pointer variable next is called a link.
Each structure is linked to a succeeding structure
by next.
60. Pictorial representation
A structure of type struct list
data next
The pointer variable next contains either
• an address of the location in memory of the
successor list element
• or the special value NULL defined as 0.
NULL is used to denote the end of the list.
61. struct list a, b, c;
a.data = 1;
b.data = 2;
c.data = 3;
a.next = b.next = c.next = NULL;
1 NULL
data next
a
2 NULL
data next
b
3 NULL
data next
c
62. Chaining these together
a.next = &b;
b.next = &c;
1
data next
a
2
data next
b
3
data next
c
NULL
What are the values of :
• a.next->data
• a.next->next->data
2
3
63. Linear Linked Lists
A head pointer addresses the first
element of the list.
Each element points at a successor
element.
The last element has a link value NULL.
64. Header file : list.h
#include <stdio.h>
#include <stdlib.h>
typedef char DATA;
struct list {
DATA d;
struct list * next;
};
typedef struct list ELEMENT;
typedef ELEMENT * LINK;
65. Storage allocation
LINK head ;
head = malloc (sizeof(ELEMENT));
head->d = ‘n’;
head->next = NULL;
creates a single element list.
n NULL
head
66. Storage allocation
head->next = malloc (sizeof(ELEMENT));
head->next->d = ‘e’;
head->next->next = NULL;
A second element is added.
n
head e NULL
67. Storage allocation
head->next=>next = malloc (sizeof(ELEMENT));
head->next->next->d = ‘e’;
head->next->next-> = NULL;
We have a 3 element list pointed to by head.
The list ends when next has the sentinel value NULL.
n
head e w NULL
68. List operations
Create a list
Count the elements
Look up an element
Concatenate two lists
Insert an element
Delete an element
69. Produce a list from a string
(recursive version)
#include “list.h”
LINK StrToList (char s[]) {
LINK head ;
if (s[0] == ‘0’)
return NULL ;
else {
head = malloc (sizeof(ELEMENT));
head->d = s[0];
head->next = StrToList (s+1);
return head;
}
}
70. #include “list.h”
LINK SToL (char s[]) {
LINK head = NULL, tail;
int i;
if (s[0] != ‘0’) {
head = malloc (sizeof(ELEMENT));
head->d = s[0];
tail = head;
for (i=1; s[i] != ‘0’; i++) {
tail->next = malloc(sizeof(ELEMENT));
tail = tail->next;
tail->d = s[i];
}
tail->next = NULL;
}
return head;
}
list from a string
(iterative version)
71. ?
A
head
tail
1. A one-element list
2. A second element is attached
A
head
tail
?
?
3. Updating the tail
A
head
tail
?
B
4. after assigning NULL
A
head
tail
NULL
B
72. /* Count a list recursively */
int count (LINK head) {
if (head == NULL)
return 0;
return 1+count(head->next);
}
/* Count a list iteratively */
int count (LINK head) {
int cnt = 0;
for ( ; head != NULL; head=head->next)
++cnt;
return cnt;
}
73. /* Print a List */
void PrintList (LINK head) {
if (head == NULL)
printf (“NULL”) ;
else {
printf (“%c --> “, head->d) ;
PrintList (head->next);
}
}
74. /* Concatenate two Lists */
void concatenate (LINK ahead, LINK bhead) {
if (ahead->next == NULL)
ahead->next = bhead ;
else
concatenate (ahead->next, bhead);
}
75. Insertion
Insertion in a list takes a fixed amount of
time once the position in the list is found.
A C
p2
p1
B
q
Before Insertion
76. Insertion
/* Inserting an element in a linked list. */
void insert (LINK p1, LINK p2, LINK q) {
p1->next = q;
q->next = p2;
}
A C
p2
p1
B
q
After Insertion
79. Delete a list and free memory
/* Recursive deletion of a list */
void delete_list (LINK head) {
if (head != NULL) {
delete_list (head->next) ;
free (head) ; /* Release storage */
}