0% found this document useful (0 votes)
8 views96 pages

Structure LinkedList4

The document discusses structures in C programming. It defines a structure called "account" with members like account number, type, name, and balance. It then declares an array of this structure called "customer" to hold multiple account records. Functions are provided to input and output data from the customer structure array. Examples are given to demonstrate accessing specific members of the account structure for a given customer element.

Uploaded by

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

Structure LinkedList4

The document discusses structures in C programming. It defines a structure called "account" with members like account number, type, name, and balance. It then declares an array of this structure called "customer" to hold multiple account records. Functions are provided to input and output data from the customer structure array. Examples are given to demonstrate accessing specific members of the account structure for a given customer element.

Uploaded by

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

MA 511: Computer Programming

Lecture 11: Structure

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
structures
array: Data Structure whose elements are all of the same data type.
Example:
int A[10]; float B[10];
structure: individual elements can differ in type:
Example:
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
};
where acct_no, acct_type, name[80], balance are the member of
the structure account.

MA511: Computer Programming


Partha S Mandal, IITG
Contd.. structures
Example:
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
} oldcustomer, newcustomer;
• oldcustomer, newcustomer are the structure
variable of type account.
MA511: Computer Programming
Partha S Mandal, IITG
Contd.. structures
Example:
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
};
• We also can declare the structure variable follows:
• struct account oldcustomer, newcustomer;
• oldcustomer, newcustomerare the structure variable of
type account.

MA511: Computer Programming


Partha S Mandal, IITG
Contd.. structures
Example:
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
}customer[100];
• This declarations implies that customer is a 100
element array of the structures of the type
account.

MA511: Computer Programming


Partha S Mandal, IITG
Example
how to access variables acct_no, acct_type, name, balance of the struct account ?
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
};
static/external struct account customer[ ] = {12, ‘S’, “abcd”, 123.0,
13, ‘C’, “wert”, 234.0,
14, ‘S’, “rsdef”, 1234.0};
or
static/external struct account customer[ ] = {{12, ‘S’, “abcd”, 123.0}, {13, ‘C’, “wert”,
234.0},{14, ‘S’, “rsdef”, 1234.0}};

static/external : storage class

MA511: Computer Programming


Partha S Mandal, IITG
Example
how to access variables acct_no, acct_type, name, balance of the struct account ?
#include<stdio.h>
void input_data(int i){
void input_data(int i); printf("Name of the customer:");
void output_data(int i); scanf(" %[^\n]", customer[i].name);
printf("Acct_no of the customer :");
struct account {
scanf("%d", &customer[i].acct_no);
int acct_no; printf("Balance of the customer :");
char acct_type; scanf("%f", &customer[i].balance);
printf("Type of the customer ");
char name[80]; scanf(" %c", &customer[i].acct_type);
float balance; }
} customer[100];
void output_data(int i){
main(){ int i, n;
printf("\n Name of the customer: %s", customer[i].name);
printf(“No of Customers? ”); printf("\n Acct_no of the customer : %d", customer[i].acct_no);
scanf(“%d”, &n); printf("\n Balance of the customer : %f", customer[i].balance);
for(i = 0; i < n; i = i + 1) printf("\n Acct_type of the customer : %c", customer[i].acct_type);
input_data(i); }
for(i = 0; i < n; i = i + 1)
output_data(i);
} //end of the main MA511: Computer Programming
Partha S Mandal, IITG
Assignments
• Write a c-programming using struct for
detecting a set of given n randomly generated
points are belonging to a given circle* or not.
struct coordinates {
int x;
int y;
} points[100];

*The input of the circle can be taken as center


and radius.
MA511: Computer Programming
Partha S Mandal, IITG
Assignments
• Write a c-programming using struct for Semester
Performance Index (SPI)
SPI= ( U1G1 + U2G2 + ...... ) / ( U1 +U2 + ....)
The grades awarded to student are G1, G2, etc in
courses with corresponding credits U1, U2, etc.
Where G’s are from 10 to 4 and U’s are from 2 to
12.
• Write a program where input is an array of
integer, then use a function for sorting the array,
finally print the sorted array from main.
MA511: Computer Programming
Partha S Mandal, IITG
MA 511: Computer Programming
Lecture 12: Structure contd. and Union

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Example
how to access variables acct_no, acct_type, name, balance of the struct account ?
#include<stdio.h>
void input_data(int i){
void input_data(int i); printf("Name of the customer:");
void output_data(int i); scanf(" %[^\n]", customer[i].name);
printf("Acct_no of the customer :");
struct account {
scanf("%d", &customer[i].acct_no);
int acct_no; printf("Balance of the customer :");
char acct_type; scanf("%f", &customer[i].balance);
printf("Type of the customer ");
char name[80]; scanf(" %c", &customer[i].acct_type);
float balance; }
} customer[100];
void output_data(int i){
main(){ int i, n;
printf("\n Name of the customer: %s", customer[i].name);
printf(“No of Customers? ”); printf("\n Acct_no of the customer : %d", customer[i].acct_no);
scanf(“%d”, &n); printf("\n Balance of the customer : %f", customer[i].balance);
for(i = 0; i < n; i = i + 1) printf("\n Acct_type of the customer : %c", customer[i].acct_type);
input_data(i); }
for(i = 0; i < n; i = i + 1)
output_data(i);
} //end of the main MA511: Computer Programming
Partha S Mandal, IITG
typedef
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
} customer[100];

int i, j; equivalent to typedef int mydef;

mydef i, j;
typedef struct {
int acct_no;
char acct_type;
char name[80];
float balance;
} account ;
account customer[100], oldcustomer, newcustomer;
MA511: Computer Programming
Partha S Mandal, IITG
Member of a struct may be a struct
Equivalent to:
typedef struct { struct date {
int day; int day;
int month;
int month;
int year;
int year; };
} date; struct account {
typedef struct { int acct_no;
int acct_no; char acct_type;
char acct_type; char name[80];
char name[80]; float balance;
float balance; struct date update;
date update; };
struct account customer[100];
} account;
account customer[100];
customer[i].acct_no: variable of the structure account
customer[i].update.month: variable of the structure date
MA511: Computer Programming
Partha S Mandal, IITG
Member of a struct may be a struct and so on

typedef struct { typedef struct {


int day; int sec;
int month; int min;
int year; int hrs;
TIME time; } TIME;
} date;
typedef struct {
int acct_no;
char acct_type;
char name[80];
float balance;
date update;
} account;
account customer[100];

customer[i].acct_no: variable of the structure account


customer[i].update.month: variable of the structure date
customer[i].update.time.min: variable of the structure TIME
Example
how to access variables acct_no, acct_type, name, balance of the struct account ?
#include<stdio.h>
void input_data(int i){
void input_data(int i); printf("Name of the customer:");
void output_data(int i); scanf(" %[^\n]", customer[i].name);
printf("Acct_no of the customer :");
struct account {
scanf("%d", &customer[i].acct_no);
int acct_no; printf("Balance of the customer :");
char acct_type; scanf("%f", &customer[i].balance);
printf("Type of the customer ");
char name[80]; scanf(" %c", &customer[i].acct_type);
float balance; }
} customer[100];
void output_data(int i){
main(){ int i, n;
printf("\n Name of the customer: %s", customer[i].name);
printf(“No of Customers? ”); printf("\n Acct_no of the customer : %d", customer[i].acct_no);
scanf(“%d”, &n); printf("\n Balance of the customer : %f", customer[i].balance);
for(i = 0; i < n; i = i + 1) printf("\n Acct_type of the customer : %c", customer[i].acct_type);
input_data(i); }
for(i = 0; i < n; i = i + 1)
output_data(i);
} //end of the main MA511: Computer Programming
Partha S Mandal, IITG
Union
Union tag { Union account {
int acct_no;
member 1;
char acct_type;
… char name[80];
member m; float balance;
}; };
• Like structures, contain members whose individual data types may
differ from one another.
• union allocates the memory equal to the maximum memory
required by the member of the union but structure allocates the
memory equal to the total memory required by the members.
• In union, one block is used by all the member of the union but in
case of structure, each member have their own memory space
• Union is useful for application where values need not be assigned
to all of the members simultaneously.

MA511: Computer Programming


Partha S Mandal, IITG
MA 511: Computer Programming
Lecture 13: Pointer

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
pointers
• Is a variable that represents the location
(address) of a data item.
• Each data item occupies one or more contiguous
memory cells in computer memory.
• No of memory cells depends on the type of data
item.
– A single character needs 1 byte (8bits)
– An integer usually needs 2 contiguous bytes
– A floating point no needs 4 contiguous bytes
– Double-precision quantity may needs 8 contiguous
bytes
pointers
• Let v is a variable of some data item.
float v;
• Then data item can then be assessed if we know the location of first
memory cell.
• &v = address of v’s memory location.

pv = &v; // & unary operator, address operator


pv = pointer of the variable v
v = *pv;// * unary operator, indirection operator
v, *pv = represent same data type.
Now if pv = &v and u = *pv then u and v represent the same value.
pv

v
22ccbc

&pu
Example: pointers
22CCC4
22ccb8 pu
3
&pv u
#include<stdio.h> 22CCC0
main(){ pv 3
int u = 3, v;
int *pu, *pv; // pointer to an integer
pu = &u; // assign add of u to pu
v
v = *pu; // assign value of u to v
pv = &v; // assign add of v to pv
printf(“u=%d &u = %X pu = %x *pu =%d\n”, u, &u, pu, *pu);
printf(“v=%d &v = %X pv = %x *pv =%d\n”, v, &v, pv, *pv);
}
Output:
u=3 &u = 22CCC4 pu = 22ccc4 *pu =3
v=3 &v = 22CCC0 pv = 22ccc0 *pv =3
Example: pointers

22ccbc
&pu
22CCC4

22ccb8 pu 3
&pv u
22CCC0

pv 3
v
Assignment
• Swap values of two variables using function
and passing pointer as arguments.
swap
/* swap values of two variables using function and passing pointer as arguments */
void swap(int *a, int *b){
int temp;
temp = *a; Output:
*a = *b; x= 15 y= 24, px = 22ccc4, py = 22ccc0
*b = temp; x= 24 y= 15, px = 22ccc4, py = 22ccc0
}
main(){
int x = 15, y = 24, *px, *py;
px = &x; py = &y;
printf("x= %d y= %d, px = %x, py = %x\n", x, y, px, py);
swap(px, py);
printf("x= %d y= %d, px = %x, py = %x\n", x, y, px, py);
}
swap
/* swap values of two variables using function and passing pointer as arguments */
void swap(int *a, int *b){
int temp;
temp = *a; Output:
*a = *b; x= 15 y= 24, &x = 22ccc4, &y = 22ccc0
*b = temp; x= 24 y= 15, &x = 22ccc4, &y = 22ccc0
}
main(){
int x = 15, y = 24;
printf("x= %d y= %d, &x = %x, &y = %x\n", x, y, &x, &y);
swap(&x, &y);
printf("x= %d y= %d, &x = %x, &y = %x\n", x, y, &x, &y);
}
MA 511: Computer Programming
Lecture 14: Pointer contd.

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Passing Arguments to Function

• Passing values (call by value)


• Passing pointers (call by reference)
• Passing a pointer to an array
Passing values
• Passing values is known as call by value.
• You actually pass a copy of the variable to the function.
• If the function modifies the copy, the original remains unaltered.
Following example demonstrated call by value.
int func(int m, int n){
int i;
i = m + n;
return i; Output:
} i before call the func 1
int main(void) { i after func is executed 1 and j= 2.
int i=1, j;
printf("i before call the func %d", i);
j= func(i, i);
printf(“i after func is executed %d and j = %d. \n", i, j);
return 0;
}
Passing pointers
• This is known as call by reference.
• We do not pass the data to the function, instead
we pass a pointer to the data.
• This means that if the function alters the data, the
original is altered.
• Following example demonstrated call by reference.
Passing pointers contd.
void func(int *p) {
++*p; /* Add 1 to the value */
return;
}
int main(void) {
int i=4, *ptri;
ptri = &i;
printf("i before call the func %d\n", i); Output:
printf(" *ptri is %d\n", *ptri); i before call the func 4
func(ptri); *ptri is 4
i after call the func 5
printf(" i after call the func %d\n", i);
return 0;
}
Passing a pointer to an array
// how to access values of a array using pointers
#define SIZE_ARRAY 2
void func(int*); // Function declaration
Int main(void){
int A[SIZE_ARRAY]={14, 16}; // array declaration
int count=0;
for (count=0; count<SIZE_ARRAY; count++)
printf(“ A before call the func %d ptri = %x\n", A[count], A+count);
func(A); // Function call
for (count=0; count<SIZE_ARRAY; count++)
printf(" A after call the func %d. Ptri = %x\n", A[count], A+count);
return 0;
}
Output:
i before call the func 14 ptri = 22ccc0
void func(int *ptr) {
i before call the func 16 ptri = 22ccc4
++*ptr; // Add 1 to the first element in the array
i after call the func 15 Ptri = 22ccc0
++*(ptr+1); // And the second element
i after call the func 17 Ptri = 22ccc4
}
MA 511: Computer Programming
Lecture 15: Pointer contd.

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
outline

• Passing a pointer to a character string


• Passing a pointer to a character
• Function returning a pointer
• Pass function pointer as parameter
Passing pointer to a character string
// how to access character of an array using pointers
void func(char *array_f){
printf("%s %p\n", array_f, array_f);
array_f +=4; // Modify the pointer
*array_f = 'x’; // Modify the data pointed to by 'array‘
}
Int main(void){
char array_s[10]="987654321"; // initialization
func(array_s); // function call
printf("%s, %p\n", array_s, array_s);
return 0;
Output:
} 987654321 22ccb0
9876x4321, 22ccb0
Passing pointer to a character
// how to access and modify pointer to a char
void func(char *ptrc){
printf("%c\n", *ptrc);
*ptrc = 'x’; // Modify the data
}
Int main(void){
char achar = 'h’; // initialization
func(&achar); // function call
printf("%c, %x\n", achar, &achar);

return 0; Output:
h
} x, 22ccc7
Passing pointer to an array
Example 1: Example 2:
void func(int *p); void func(int p[]);
int main(void){ int main(void){
static int a[5]={10,20,30,40,50}; static int a[5]={10,20,30,40,50};
func(a + 3); func(a + 3);
return 0; return 0;
} }
void func(int *p){ void func(int p[ ]){
int i, sum = 0; int i, sum = 0;
for(i=0; i<2; i++) for(i=0; i<2; i++)
sum += *(p+i); sum += *(p+i);
printf(“sum = %d”, sum); printf(“sum = %d”, sum);
} }
Assignments
• Polynomial addition
• Polynomial multiplication
MA 511: Computer Programming
Lecture 16: Pointer Contd.

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
• A function can return a pointer
• Passing function to other function
• A function can return a pointer
• Program to pass function pointer as
parameter
– how to pass function itself as a parameter to
another function.
A function can return a pointer
• C program allows to return an array from a function
• C program allows to return a pointer from a function
with following prototype.
int * Function() {

. . .
return ptr;
}

• Pointers to local variables become invalid when the


function exits.
• So, we need to define the local variable
as static variable for returning local
Example: A function can return a pointer

int *func(int *p);


main(){ int *func(int *p){
int a[5]={10,20,30,40,50}; int i, imax, max = 0;
int *maxptr; for(i=0; i<5; i++){
maxptr = func(a); if(*(p+i) > max){
printf(“max=%d”, *maxptr); max =*(p+i);
} imax = i;
}
}
return(p+imax);
}
MA511: Computer Programming
Partha S Mandal, IITG
Pass function pointer as parameter

• We can only pass variables as parameter to


function
• We cannot pass function to another function as
parameter. But, we can pass function reference
to another function using function pointers.
• Using function pointer, we can store reference of
a function and can pass it to another function as
normal pointer variable.
• Finally in the function we can call function
pointer as normal functions.
Example: Passing function to other function
float guest1(float x, float y);
float guest2(float x, float y);
float host(float (*pt) (float x, float y));
float guest1(float x, float y){
int main(){
float x, y; return(x+y);
}
x = host(guest1); float guest2(float x, float y){
printf(“x = %f\n",x);
y = host(guest2); return(x*y);
printf(“y = %f\n",y); }
return 0; float host(float (*pt) (float x, float y)){
} /* end of main */ float a=5.0, b=3.5, c;
c=(*pt)(a,b);
return(c);
}
MA 511: Computer Programming
Lecture 17: Pointer Contd.
Pointer & multidimensional arrays

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Pointers, Arrays, Multidimensional Arrays
• Pointers versus arrays
– Lots of similarities

• How to deal with 2D, 3D, multidimensional


arrays (for storing matrices and other 2D or 3D
data!)
Array Name
ffe2de0c ffe2de10 ffe2de14 ffe2de18
The array name is a
list 1 2 3 4
pointer to the first
element of the array [0] [1] [2] [3]

int list[]={1,2,3,4};
printf(“%x, %x, %d”, list, &list[0], *list);

Output: ffe2de0c ffe2de0c 1


Pointers and Arrays p

list 1 2 3 4
int *p,
int list[]={1,2,3,4}; [0] [1] [2] [3]
p = list; /* equivalent to p = &list[0] */
printf(“%d\n”, *p); /* prints the value “1” */

You can use a


pointer to access
the array
Pointer and []
P

Any pointer to a block of memory


can use the [] syntax, even if it is
not declared as an array! List 1 2 3 4

[0] [1] [2] [3]


int *p,
int list[]={1,2,3,4}; int *v; and int v[]; /* Mean the same thing */
p = list;
printf(“%d\n”, p[2]); // prints 3
Array indexing []
*list – Contents pointed to by list
list list + 2
*(list + 2) – Contents at list[2]
ffe2de0c ffe2de10 ffe2de14 ffe2de18 Indexing an array is just a way
1 2 3 4 of finding a particular address
in that block
[0] [1] [2] [3]

int list[] = {1,2,3,4} // array of 4 ints


printf(“%d”, list[2]);
This is equivalent to
printf(“%d”,*(list+2));
Pointer Arithmetic
When we add to a pointer, such as (p + 1), we
don’t literally add 1 to the pointer address

Instead we add one “address” to the pointer


p p+1 p+2 p+3

ffe2de0c ffe2de10 ffe2de14 ffe2de18

1 2 3 4

[0] [1] [2] [3]


Pointer Arithmetic
int list[] = {1, 2, 3, 4};
int *p = list; /* same as p = &list[0] */
printf(“%x”,p); /* prints ffe2de0c */

ffe2de0c ffe2de10 ffe2de14 ffe2de18

1 2 3 4
Pointer Arithmetic
int list[] = {1, 2, 3, 4};
int *p = list; /* same as p = &list[0] */
printf(“%x”,p); /* prints ffe2de0c */
p = p + 1; /* p increases by 4 */
printf(“%x”,p); /* prints ffe2de10 */

p
Think of pointer
arithmetic as add
1 “location” ffe2de0c ffe2de10 ffe2de14 ffe2de18

instead of one 1 2 3 4
byte or address.
Pointer Arithmetic
double list2[] = {1.0, 2.0, 3.0};
double *p = list2; /* same as p = &list2[0] */
printf(“%x”, p); /* prints ffe2de0c */

ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0 2.0 3.0


Pointer Arithmetic
double list2[] = {1.0, 2.0, 3.0};
double *p = list2; /* same as p = &list2[0] */
printf(“%x”,p); /* prints ffe2de0c */
p = p + 1; /* P increases by 8 bytes */
printf(“%x”,p); /* prints ffe2de14 */

ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0 2.0 3.0


Pointer Arithmetic on Arrays

• *(list+1) references the next element in the


array (equivalent to list[1])

• Be careful: *(++list) works too but now we


have lost our pointer to the beginning of the
array!!!
– Equivalent to: list = list + 1; *list;
2D Arrays

int cave[ArraySize][ArraySize];
Column
0 1 2 3

0 1 2 3 4
1
5 6 7 8
Row
2 9 10 11 12
3 13 14 15 16
2D Arrays
int myMatrix[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
Column
0 1 2 3

0 1 2 3 4 myMatrix[0][1] → 2
1
Row 5 6 7 8
2 9 10 11 12
myMatrix[2][3] → 12
myMatrix[row][col]
Physically, in one block of memory
int myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} };
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

1 2 3 4 5 6 7 8

row 1 row 2

Array elements are stored in row major order


Row 1 first, followed by row2, row3, and so on
2D Array Name and Addresses
int myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} };

ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

1 2 3 4 5 6 7 8

myMatrix: pointer to the first element of the 2D array


myMatrix[0]: pointer to the first row of the 2D array
myMatrix[1]: pointer to the second row of the 2D array
*myMatrix[1] is the element of myMatrix[1][0]
Accessing 2D Array Elements
int myMatrix[2][4] = { {1,2,3,4} , {5,6,7,8} };

1 2 3 4 5 6 7 8

Indexing: myMatrix[i][j] is same as


*(myMatrix[i] + j)
(*(myMatrix + i))[j]
*((*(myMatrix + i)) + j)
*(&myMatrix[0][0] + 4*i + j)
Pointer & Multidimensional Array
x: 2D array having 10 rows 20 columns
declare as:
int (*x)[20]; a ptr to a group of contiguous one dimensional,
20-element integer array.
which is same as
int x[10][20];

Similarly for 3D array:


int (*b)[20][30]; a ptr to a group of contiguous two
dimensional, 20 X 30 integer arrays.
which is same as
int b[10][20][30];
Pointer & Multidimensional Array
int (*x)[20]; a ptr to a group of contiguous one dimensional,
20-element integer array.
Or int x[10][20];
x 0 1 2 19

(x + 1)

(x + 9)
Pointer & Multidimensional Array
How to access the item in row 3 and column 4
x[2][3] or *(*(x+2) + 3)
x 0 1 2 3 19
0

(x + 1) *x
1

(x + 2) *(x + 1)

*(x + 2) *(x + 2) + 3 *(*(x + 2) + 3)


Exercise
1. int X[8] ={10, 12, 14, 15, 16, 17, 18, 19}; What is
a) X
b) (x+2)
c) *x
d) *x+2
e) *(x+2) ?

2. float table[2][3] = { {1.1, 1.2, 1.3}, {2.1, 2.2, 2.3} }; What is


a) table,
b) (table +1)
c) *(table +1)
d) (*table +1) + 1
e) (*(table) +1)
f) *(*(table +1)+1
g) *(*(table +1))
h) *(*(table) +1) + 1?
MA 511: Computer Programming
Lecture 18:
Dynamic memory allocation

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Dynamic memory allocation
int x[10];
Or
int *x;
x = (int *) malloc(10*sizeof(int));
• malloc library function reserves a block of
memory size is equivalent to 10 integer for the
above example.
• stdlib.h or malloc.h header file is required.
• malloc returns a pointer to the beginning of the
allocated space.
• in general malloc(a) allocate a bytes of memory.
Example: Dynamic memory in 1D
#include<stdio.h>
#include<stdlib.h>
main(){
int *a, i, n;
printf("Type n");
scanf("%d",&n);
a = (int *)malloc(n*sizeof(int));

for(i=0; i<n; i++){


printf("type %d entry ",i);
scanf("%d", a+i);
}
for(i=0; i<n; i++){
printf("%d", *(a+i));
}
}
Example: Dynamic memory in 2D
#include<stdio.h>
#include<stdlab.h>
#define ROW 50
void read_ip(int *a[ROW], int nrow, int ncol); void read_ip(int *a[ROW], int m, int n){
void write_op(int *a[ROW], int nrow, int ncol); int row, col;
main(){ for(row =0; row<m; row++)
int *a[ROW], nrow, ncol, i; for(col =0; col<n; col++)
Printf(“Type no of rows & cols”); scanf(“%d”, (a[row]+col));
scanf(“%d%d”,&nrow, &ncol);
for(i=0; i<=nrow; i++){
}
void write_op(int *a[ROW], int m, int n){
a[i]=(int *) malloc(ncol*sizeof(int));
int row, col;
}
for(row =0; row<m; row++){
read_ip(a, nrow, ncol);
for(col =0; col<n; col++)
write_op(a, nrow, ncol);
printf(“%4d”, *(a[row]+col));
}
printf(“\n”);
}
}
MA 511: Computer Programming
Lecture 19: Pointer to structure and
passing structures to functions

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Structures and pointers
typedef struct { struct account{
int acct_no; int acct_no;
char acct_type; char acct_type;
char name[80]; char name[80];
float balance; float balance;
} account;
} customer, *ptr;
account customer, *ptr;
ptr = &customer;
ptr = &customer;
MA511: Computer Programming
Partha S Mandal, IITG
Structures and pointers
typedef struct {
int month;
int day;
int year;
} date;

typedef struct {
int acct_no;
char acct_type;
char name[80];
float balance;
date lastpayment;
} customer, *ptr = &customer;

MA511: Computer Programming


Partha S Mandal, IITG
Example: Structures and pointers
ptr->acct_no = 12341; //customer.aact_no = 12341;
ptr->acct_type = "S/B"; //customer.acct_type ="S/B";
main(){ ptr->name = "xyz"; //customer.name = "xyz";
ptr->balance = 2345.00; //...
typedef struct { ptr->lastpayment.month=02;
int month; ptr->lastpayment.day=15;
ptr->lastpayment.year=2009;
int day;
int year; printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
} date; printf("AccNo=%d, Balance=%f, Year=%d\n",
ptr->acct_no, ptr->balance, ptr->lastpayment.year );
struct {
}
int acct_no;
char *acct_type; Account= S/B Name=xyz
char *name; AccNo=12341, Balance=2345.000000
float balance;
date lastpayment;
} customer, *ptr = &customer;
MA511: Computer Programming
Partha S Mandal, IITG
Example: Structures and pointers
ptr->acct_no = 12341; //customer.aact_no = 12341;
ptr->acct_type = "S/B"; //customer.acct_type ="S/B";
main(){
ptr->name = "xyz"; //customer.name = "xyz";
ptr->balance = 2345.00; //...
typedef struct {
ptr->lastpayment.month=02;
int month;
ptr->lastpayment.day=15;
int day;
ptr->lastpayment.year=2009;
int year;
} date;
printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
printf("AccNo=%d, Balance=%f, Year=%d\n",
typedef struct {
ptr->acct_no, ptr->balance, ptr->lastpayment.year );
int acct_no;
char *acct_type;
}
char *name;
float balance;
Account= S/B Name=xyz
date lastpayment;
AccNo=12341, Balance=2345.000000
} account;

account customer, *ptr = &customer;

MA511: Computer Programming


Partha S Mandal, IITG
Passing structures to functions
main(){
typedef struct { account customer, *ptr;
ptr = &customer;
int acct_no;
ptr->acct_no = 12341; //customer.aact_no = 12341;
char *acct_type; ptr->acct_type = "S/B"; //customer.acct_type ="S/B";
char *name; ptr->name = "xyz"; //customer.name = "xyz";
ptr->balance = 2345.00; //...
float balance;
printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
} account; printf("AccNo=%d, Balance=%f\n", ptr->acct_no, ptr->balance);

get_data(ptr); //get_data(&customer);
void get_data(account *p){
printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
p->acct_no = 55555; printf("AccNo=%d, Balance=%f\n", ptr->acct_no, ptr->balance);
p->acct_type = "C/A"; }
p->name = "abc"; Account= S/B Name=xyz
AccNo=12341, Balance=2345.000000
p->balance = 777777.00;Account= C/A Name=abc
AccNo=55555, Balance=777777.000000
}

MA511: Computer Programming


Partha S Mandal, IITG
Passing structures to functions
main(){
typedef struct { account customer, *ptr;
ptr = &customer;
int acct_no;
ptr->acct_no = 12341; //customer.aact_no = 12341;
char acct_type[10]; ptr->acct_type = "S/B"; //customer.acct_type ="S/B";
char name[80]; ptr->name = "xyz"; //customer.name = "xyz";
ptr->balance = 2345.00; //...
float balance;
printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
} account; printf("AccNo=%d, Balance=%f\n", ptr->acct_no, ptr->balance);

get_data(ptr); //get_data(&customer);
void get_data(account *p){
printf("Account= %s Name=%s\n", ptr->acct_type, ptr->name);
p->acct_no = 55555; printf("AccNo=%d, Balance=%f\n", ptr->acct_no, ptr->balance);
p->acct_type = "C/A"; }
p->name = "abc"; Account= S/B Name=xyz
AccNo=12341, Balance=2345.000000
p->balance = 777777.00;Account= C/A Name=abc
AccNo=55555, Balance=777777.000000
}

MA511: Computer Programming


Partha S Mandal, IITG
Passing structures to functions
main(){
# define N 2 account customer[N], *ptr, *ptr1;
typedef struct { ptr = customer, ptr1=customer;
int acct_no; int i;
char *acct_type; for(i=0; i<N; i++){
ptr1=get_data(ptr+i); //get_data(customer+i);
char *name;
float balance; printf("Account= %s Name=%s\n", ptr1->acct_type,
} account; ptr1->name);
printf("AccNo=%d, Balance=%f\n", ptr1->acct_no,
account *get_data(account *p){ ptr1->balance);
}
p->acct_no = 55555; }
p->acct_type = "C/A";
p->name = "abc"; Account= C/A Name=abc
p->balance = 777777.00; AccNo=55555, Balance=777777.000000
return(p) Account= C/A Name=abc
AccNo=55555, Balance=777777.000000
}

MA511: Computer Programming


Partha S Mandal, IITG
Passing structures to functions
main(){
# define N 2 account customer[N], *ptr, *ptr1;
typedef struct { ptr = customer, ptr1=customer;
int acct_no; int i;
char acct_type[10]; for(i=0; i<N; i++){
ptr1=get_data(ptr+i); //get_data(customer+i);
char name[80];
float balance; printf("Account= %s Name=%s\n", ptr1->acct_type,
} account; ptr1->name);
printf("AccNo=%d, Balance=%f\n", ptr1->acct_no,
account *get_data(account *p){ ptr1->balance);
}
p->acct_no = 55555; }
p->acct_type = "C/A";
p->name = "abc"; Account= C/A Name=abc
p->balance = 777777.00; AccNo=55555, Balance=777777.000000
return(p) Account= C/A Name=abc
AccNo=55555, Balance=777777.000000
}

MA511: Computer Programming


Partha S Mandal, IITG
MA 511: Computer Programming
Lecture 20: Linked list

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
Self-Reference Structure
struct tag {
list_of_no structure looks like
member 1;
member 1;
….. data next
struct tag *name;
};
Example:
struct list_of_no { It contains
int data; the info/data It contains an
struct list_of_no *next; address of
}; the structure
It’s a structure of type list_of_no. there are two members;
1. data is a integer type and
2. next is a pointer to a structure of the same type, i.e., a pointer to a structure of
type list_of_no.
Linked Lists using
Self-Reference Structure
struct list_of_no {
int data;
struct list_of_no *next;
};

typedef struct list_of_no node;


node *start;
start = (node *) malloc(sizeof(node));

1c4a80 1c4a82 1c4a84


start data next data next data next

101 1c4a80 71 1c4a84 19 NULL


How to create a linked list recursively?
void create(node *temp){
#include<stdio.h>
node *temp1;
#include<stdlib.h>
char val;
struct list_of_no {
printf(“Type Y for continue N for stop:”);
int data;
scanf(“ %c”, &val));
struct list_of_no *next;
if(val==‘Y’) {
}; temp1 = (node *) malloc(sizeof(node));
typedef struct list_of_no node;
printf(“Type int data for next node: ”);
void create(node *pt);
scanf(“%d”, &(temp1->data));
void print(node *pt);
temp1->next = NULL;
int main(){ temp->next = temp1;
node *start; create(temp1);
start = (node *) malloc(sizeof(node)); }
printf(“Type int data for 1st node: ”); }
scanf(“%d”, &(start->data)); void print(node *temp){
start->next = NULL; while(temp){
create(start); printf("|%d |->", temp->data);
print(start); temp=temp->next;
} }
}
temp1
start data next data next
temp
17 NULL 10 NULL
Storage class
• auto: default storage class for local variables.
auto int Month;
• register: local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can’t have the unary '&'
operator applied to it (as it does not have a memory location).
register int Miles;
• static: default storage class for global variables, it can also be
defined within a function. If this is done, the variable is initialized at
compilation time and retains its value between calls.
• extern: global variable that is visible to ALL object modules. When
you use 'extern' the variable cannot be initialized as all it does is
point the variable name at a storage location that has been
previously defined.
MA 511: Computer Programming
Lecture 21: Linked list – create, insert, search

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
How to insert node to a linked list?
node *insert(node *list){
node *search(node *, int);
1. At the beginning of the list node *newnode, *target;
2. At the middle of the list int target_no;
printf(“insert node before target data, type target ”);
3. At the end of the list scanf(“%d”, &target_no);
: if(list->data == target_no){ // add at the beginning
: newnode = (node *) malloc(sizeof(node));
printf(“type new data to insert”);
scanf(“%d”, &(newnode->data));
newnode->next= list;
node *insert(node *pt); list = newnode;
}
else{ // finder return ptr of the preceding to the target node
main(){ target = search(list, target_no);
node *start; if (target ==NULL) printf(“target no is not in list”);
start = (node*)malloc(sizeof(node)); else { // add in the middle of the list
newnode = (node *) malloc(sizeof(node));
create(start);
printf(“type new data to insert”);
print(start); scanf(“%d”, &(newnode->data));
start=insert(start); newnode->next = target->next;
print(start); terget->next= newnode;
} }
}
return(list);
}
Searching the target node
node *search(node *temp, int target_no){
//return a ptr to the node before the target node
while(1){
if(temp->next->data==target_no)
return(temp);
else if(temp->next->next==NULL)
return(NULL);
else temp=temp->next;
}
}

temp
temp
number next number next number next
102 112 122

number next
target_no :122
999 NULL
How to insert node in middle of the list?
newnode = (node *) malloc(sizeof(node));
scanf(“%d”, &(newnode->data));
newnode->next = target->next;
target ->next= newnode;

start target
number next number next
X
102 112 122 NULL

newnode
115
How to insert node at the beginning of the list?

newnode = (node *) malloc(sizeof(node));


scanf(“%d”, &(newnode->data));
newnode->next= start;
start = newnode;

number next number next number next


start X 102 112 122 NULL

newnode
next

80
Assignment
• Write a C-Program for inserting a new node in
a linked list after the target data (or key). The
key value of a new node and target key should
be given from the terminal.
• Write a C-Program for inserting a new node in
a linked list maintaining order with respect to
the key value of nodes. The key value of a new
node should be given from the terminal.
MA 511: Computer Programming
Lecture 22: Linked list – Deletion

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
How to delete node from a linked list?
node *delete(node *list){
node *search(node *, int);
node *delete(node *start) node *temp, *target;
int target_no;
node *search(node*, int) printf(“Type target key to be deleted”);
node *target, *temp; scanf(“%d”, &target_no);
if(list->data == target_no){ delete from beginning
int target_no; temp= list->next;
free(list);
list = temp;
main(){ }
else{ finder return ptr of the preceding to the target node
node *start; target = search(list, target_no);
if (target ==NULL) printf(“target key is not in list”);
start = (node*)malloc(sizeof(node)); else { delete from the middle of the list
create(start); temp = target->next->next;
free(target->next);
print(start); target->next= temp;
}
start=delete(start); }
print(start); return(list);
}
}
Assignment

• Write a C-Program for deleting a node located


just before the target node. The key value of
the target node should be entered from the
terminal.
• Write a C-Program for deleting a node from the
linked list, the following node of the target
node with a given key value. The key value
should be given from the terminal.
MA 511: Computer Programming
Lecture 23: Linked list – Circular linked list
and link reversal

Partha Sarathi Mandal


[email protected]
Dept. of Mathematics, IIT Guwahati
How to create a Circular linked list ?
void create(node *head){
node *temp=head, *temp1;
struct list_of_no { char c_value;
int data; while(1){
printf(“Type “Y” to continue Type “N” to stop: ”);
struct list_of_no *next; scanf(“ %c”, &c_value);
}; if(c_value==‘N’){ temp->next = head; break;
}
typedef struct list_of_no node; else{ temp1 = (node *) malloc(sizeof(node));
void create(node *pt); scanf(“%d”, &(temp1->data));
temp->next = temp1;
void print(node *pt); temp=temp->next;
main(){ }
}

node *start; void print(node *head){


node *temp=head;
start = (node *) malloc(sizeof(node)); printf("%d-> ", temp->data);
scanf(“%d”, &start->data); temp=temp->next;
create(start); while(!(temp==head)){
printf("%d-> ", temp->data);
print(start); temp=temp->next;
} temp1 }
printf("%d-> ", temp->data);
start }
number next number next number next
temp
102 112 123
Linked reversal
struct list_of_no {
int data;
struct list_of_no *next; node *reverseLinked(node *head) {
}; node *previous, *current, *next;
typedef struct list_of_no node; previous = NULL;
void create(node *pt); current = head;
void print(node *pt); while (current != NULL) {
node *ReverseLink(node *pt); next = current->next;
main(){ current->next = previous;
node *start; previous = current;
start = (node *) malloc(sizeof(node)); current = next;
scanf(“%d”, &start->data); }
create(start); return previous;
print(start); }
start=ReverseLink (start);
print(start);
MA511: Computer Programming
} Partha S Mandal, IITG
Assignments
1. Write a C-Program for inserting a new node in
a circular linked list (i) before a target key, (ii)
after a target key.
2. Write a C-Program for deleting a node from
the circular linked list (i) preceding to give key
(ii) after a give key (iii) node containing the key
value.
– where target key, key value of the inserting node
and deleting node should enter in from the
terminal MA511: Computer Programming
Partha S Mandal, IITG
Assignments
1. Write a c program for creating a doubly linked
list with a Loop or recursive function.
2. Write a C-Program for inserting a new node in a
doubly linked list (i) before a target key, (ii) after a
target key.
3. Write a C-Program for deleting a node from the
doubly linked list (i) preceding to give key (ii)
after a give key (iii) node containing the key
value.
– where target key, key value of the inserting node and
deleting node should enter in from the console.

MA511: Computer Programming


Partha S Mandal, IITG

You might also like