1 - C-Review - V2
1 - C-Review - V2
• Today’s agenda
– Brief idea how to act in a zoom lecture
– Introducing the instructor
– Course overview and brief idea about syllabus
– C review (as much as we can)
• Pointer
• Array, 2d array
• String
• Structure
• File IO
1
C programming review
2
Starting with Fun!
3
Agenda
• In this lecture, we will review some advance topics in
C programming language
• Generally, it is assumed that you already have some
idea about these topics and a review will help you to
recall them.
• These topics are very important to understand the
subsequent advance topics and data structures that
we will learn in this course.
• If you think that you are not familiar with them, you
should spend good amount of time to review them
by this week.
4
Agenda
• Data and Memory
• Pointer review
– Declaring, dereferencing, pointer of pointer
– Function call by value and reference
• Arrays review
– Array concepts
– Array and pointers
– Passing array to a function
– 2D array
• String review
• Structure Review
• File I/O review 5
Data and Memory
6
Data and Memory
• Some very basic definitions:
• bit - a single zero or one. The word comes from the
contraction of "binary digit.
• byte - eight consecutive bits. Can store a char.
• word - the size of this depends on the computer, but they
are almost always either 2 or 4 bytes. Usually stores an int.
7
Data and Memory
• If we execute the line: char ch = 'A'
• and the variable ch happened to be stored in memory location 1000, our picture
would look like this:
…….
•
1002
1001
1000 Binary of ascii of ‘A’
……
• An integer would be stored over 4 consecutive bytes, and the address of the
variable storing the integer would be the first memory address the variable was
stored in.
• How to get a size of a variable or type?
• In certain situations, it's useful to know the size of a particular variable or
type/struct.
• The following expression returns the desired information:
• sizeof(int) or sizeof (x) //if x is a variable
8
Pointer Review
(We will briefly go through pointer
review. If you need more explanation,
please review the uploaded slide on
pointers)
9
Pointers
• A pointer can store the memory address of a variable of a
specific data type.
• Why specific data type? Because different type stored
differently and takes different size in memory.
• Example of declaring a pointer:
int *p; //You have to put * before the variable
name. Like any uninitialized variable,
here p is pointing to a garbage address as it is
not initialized yet.
- Another example bellow:
int *pointer1 = &x; // Example of both declaration and
initialization in the same line
addr of x
int x;
0x2000 1
0x9060
11
De-referencing Example
Consider this few lines of codes bellow, It will
print 1: p
q
0x9060
int *p , q; 0x2000
1
0x9060
p=&q;
printf(“%d”, *p); //this will print the value of q
• Why it is printing the value of q?
– Because, we are de-referencing p by writing *p
– The *p in the printf means, the variable it is pointing to. As
p is pointing to q, *p means actually q.
– Now you know the differences between *p in the first line
and *p in the third line
12
Summary of using * and &
• To declare a pointer add an * in front of its
name.
• To obtain the address of a variable use & in
front of its name.
• To obtain the value of a variable pointed by a
pointer, use * in front of a pointer's name.
output:
int main()
{ Pointer example p1 = 0x7ffce97158f8
p2 = 0x7ffce97158fc
*p1 = -42
*p2 = 163
int x, y;
---------
int *p1, *p2;
p1 = 0x7ffce97158f8 *p1 = 17
x = -42;
---------
y=163;
p1 = 0x7ffce97158fc *p1 = 163
p1 = &x;
---------
p2 = &y; ---------
printf("p1 = %p *p1 = %d \n", p1, *p1); p2 = 0x7ffce97158f8 *p2 = 17
printf("p2 = %p *p2 = %d \n", p2, *p2); p1 = 0x7ffce97158fc *p1 = 17
printf("---------\n"); ---------
p2 = &x;
printf("---------\n");
printf("p2 = %p *p2 = %d \n", p2, *p2);
*p1 = *p2;
printf("p1 = %p *p1 = %d \n", p1, *p1);
printf("---------");
return 0;
14
}
Testing pointer is pointing something
meaningful ( Dealing with segmentation fault)
• If a pointer is not initialized to any address, dereferencing that pointer
might result in garbage value, or can create segmentation fault/run-
time error as your code is trying to access a memory which is not
allocated to your program. In that case we can use the following
technique to prevent such potential error.
• We can assign NULL to a pointer.
• int *aPtr = NULL;
• It's important not to dereference a null pointer. Doing so will lead to a run-time
error.
• However, before dereferencing we can check it is NULL or not:
– if (aPtr) //it checks if aPtr is not NULL.
{ write statements that can use aPtr as it is safe to do so}
• The above line checks if aPtr is NULL or not.
– You could also write: if (aPtr!= NULL) //this is same as if (aPtr)
• Note that it is programmer’s responsibility to assing NULL values when necessary
15
Why to use pointer
• C programming language WANTED the programmer to
have the ability to directly manipulate memory.
16
Pointers and Function Arguments
• Call by value
• Call by reference
x: 1 x: 2
swap
y: 2 y: 1
17
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
int x = 1, y = 2;
fakeSwap(x, y);
printf(“%d %d\n”, x, y);
return 0;
}
18
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
19
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{ tmp:
int tmp; 0x2060
a:
tmp = a; 1 0x2038
a = b;
b:
b = tmp; 2 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
20
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = a; 1 0x2038
a = b;
b:
b = tmp; 2 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
21
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = a; 2 0x2038
a = b;
b:
b = tmp; 2 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
22
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = a; 2 0x2038
a = b;
b:
b = tmp; 1 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
23
#include <stdio.h>
Solution 1
void fakeSwap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
fakeSwap(x, y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
24
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main()
{
int x = 1, y = 2;
trueSwap(&x, &y);
printf(“%d %d\n”, x, y);
return 0;
}
25
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
26
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{ tmp:
int tmp; 0x2060
a:
tmp = *a; addr of x 0x2038
*a = *b;
b:
*b = tmp; addr of y 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
27
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = *a; addr of x 0x2038
*a = *b;
b:
*b = tmp; addr of y 0x2040
}
int main()
{
int x = 1, y = 2;
x:
1 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
28
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = *a; addr of x 0x2038
*a = *b;
b:
*b = tmp; addr of y 0x2040
}
int main()
{
int x = 1, y = 2;
x:
2 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
2 0x2010
return 0;
}
29
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{ tmp:
int tmp; 1 0x2060
a:
tmp = *a; addr of x 0x2038
*a = *b;
b:
*b = tmp; addr of y 0x2040
}
int main()
{
int x = 1, y = 2;
x:
2 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
1 0x2010
return 0;
}
30
#include <stdio.h>
Solution 2
void trueSwap(int* a, int* b)
{ So, truSwap
int tmp;
managed to
swap x and y!
tmp = *a;
*a = *b;
*b = tmp;
}
int main()
{
int x = 1, y = 2;
x:
2 0x2000
trueSwap(&x, &y);
printf(“%d %d\n”, x, y); y:
1 0x2010
return 0;
}
31
Call by value and call by reference example conclusion
32
Pointer of Pointer
• The concept of pointers can be further
extended.
• Pointer, we know is a variable that contains
address of another variable.
• Now this variable itself might be another
pointer.
• Thus, we now have a pointer that contains
another pointer’s address.
• The following example should make this point
clear.
33
int main( )
{
int i = 3, *j, **k ;
j = &i ;
k = &j ;// K has the capability to hold address of pointer
printf ( "\nAddress of i = %u", &i ) ; //print address of i
printf ( "\nAddress of i = %u", j ) ; //print address of i
printf ( "\nAddress of i = %u", *k ) ; //print address of i
printf ( "\nAddress of j = %u", &j ) ; //print address of j
printf ( "\nAddress of j = %u", k ) ; //print address of j
printf ( "\nAddress of k = %u", &k ) ; //print address of k
printf ( "\nValue of j = %u", j ) ; //print value of j, which is address of i
printf ( "\nValue of k = %u", k ) ; //print value of k, which is address of j
printf ( "\nValue of i = %d", i ) ; //print 3
printf ( "\nValue of i = %d", * ( &i ) ) ; //print 3
printf ( "\nValue of i = %d", *j ) ; //print print 3
printf ( "\nValue of i = %d", **k ) ; //print 3. As *k = j, and *j = i, i=3
return 0;
}
//output:
Address of i = 178371580
Address of i = 178371580 i j k
Address of i = 178371580
Address of j = 178371584 178371580 178371584
Address of j = 178371584 3
Address of k = 178371592
Value of j = 178371580 178371580 178371584 178371592
Value of k = 178371584
Value of i = 3
Value of i = 3
Value of i = 3 34
Value of i = 3
Arrays
35
Arrays
• An array is a collection of variables, with:
• 1) The items are stored in consecutive memory locations
• 2) All the variables in an array are of the same type.
Value 5 6 8 23 22 9 90 4
address 1000 1004 1008 1012 1016 1020 1024 1028
37
Pointers and Arrays
int array[size];
int* pPtr = array + i; //let’s say i is an index of the array
Type array[size];
0x2008
0 1 2 3 4
pPtr: qPtr:
float array[5];
float* pPtr = array;
float* qPtr = NULL;
40
0x2008 0x200C 0x2010 0x2014 0x2018
array:
0x2008
0 1 2 3 4
pPtr: qPtr:
float array[5];
float* pPtr = array;
float* qPtr = NULL;
Note: pPtr is not becoming 2008 to 2009. It is jumping to the next int as it is
an int pointer. It is increased by 4 as an int takes 4 bytes 41
0x2008 0x200C 0x2010 0x2014 0x2018
array:
0x2008
0 1 2 3 4
pPtr: qPtr:
float array[5];
float* pPtr = array;
float* qPtr = NULL;
42
0x2008 0x200C 0x2010 0x2014 0x2018
array:
0x2008
0 1 2 3 4
pPtr: qPtr:
float array[5];
float* pPtr = array;
float* qPtr = NULL;
0x2008
0 1 2 3 4
pPtr: qPtr:
float array[5];
float* pPtr = array;
float* qPtr = NULL;
printf("--------using p-------------\n");
p = data; // p is now &data[0]
for(i = 0; i<5; i++)
{
printf("address: %p, value: %d \n", p, *p);
p++;
} output:
address: 0x7ffd8ec91e10, value: 87, test: 87
address: 0x7ffd8ec91e14, value: 99, test: 88
return 0; address: 0x7ffd8ec91e18, value: 75, test: 89
} address: 0x7ffd8ec91e1c, value: 88, test: 90
The values of address: 0x7ffd8ec91e20, value: 93, test: 91
the array also --------using p-------------
address: 0x7ffd8ec91e10, value: 87 It is just adding i to
can be accessed data[0].
using: address: 0x7ffd8ec91e14, value: 99
address: 0x7ffd8ec91e18, value: 75 *data is dereferencing
data[i] data (which is &data[0])
*(i+data) address: 0x7ffd8ec91e1c, value: 88
45
i[data] address: 0x7ffd8ec91e20, value: 93
What is the difference between
pointer and array?
• While double values[10]; allocates 10
locations to store doubles, double *p; does
not.
• Instead double *p; only allocates the
memory to store a single location in memory.
• However, we CAN use a pointer to
dynamically allocate memory, that we will
learn later in the semester (if we get time).
46
Passing Entire Array to Function
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
What are we
int i;
printf("Original Array: ");
passing?
for(i=0; i<6; i++) Reference or value?
printf("%d ", num[i]);
50
Multidimensional Arrays
Index grid[0][0] grid[0][1] grid[1][0] grid[1][1] grid[2][0] grid[2][1] grid[3][0] grid[3][1]
Value 5 6 8 23 22 9 90 4
address 1000 1004 1008 1012 1016 1020 1024 1028
51
2D Array is an array of arrays
main( )
{
int grid[4][2] = {
{ 5, 6 },
{ 8, 23 },
{ 22, 9 },
{ 90, 4 }
} ;
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, grid[i] ) ;
}
Output:
Address of 0 th 1-D array = 2961709872
Address of 1 th 1-D array = 2961709880
Address of 2 th 1-D array = 2961709888
Address of 3 th 1-D array = 2961709896
52
Accessing 2D array using pointer
• The following are equivalent:
• s[2][1] //second row, first col
• *(s[2]+1)
• *(*(s+2)+1) //here 2 indicates
the array number
53
Accessing 2D array using pointer
main( )
{
int s[4][2] = {
{ 5, 6 },
{ 8, 23 },
{ 22, 9 },
{ 90, 4 }
} ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}
}
Output:
5 6
8 23
22 9
90 4
54
2D array as parameter
• Only first subscript may be left unspecified
• void f1(int grid[][10]) // valid
• void f3(int grid[][]); //invalid
• Generally, array sizes are also passed to functions while
dealing with 1D or multi dimensional array
• void print( int a[ ][4], int row, int col )
• The sizes allow to iterate properly and access the elements
within the ranges.
55
main( )
Accessing 2D array using pointer
{ print ( int q[ ][4], int row, int col )
int a[3][4] = { {
1, 2, 3, 4, int i, j ;
5, 6, 7, 8, for ( i = 0 ; i < row ; i++ )
9, 0, 1, 6 {
} ; for ( j = 0 ; j < col ; j++ )
printf ( "%d ", q[i][j] ) ;
print ( a, 3, 4 ) ; printf ( "\n" ) ;
} }
printf ( "\n" ) ;
display ( int *q, int row, int col ) }
{
int i, j ;
for ( i = 0 ; i < row ; i++ )
{
Our favorite one as
for ( j = 0 ; j < col ; j++ ) we are very
printf("%d ",*(q+i*col+j));
printf ( "\n" ) ; familiar with this
}
printf ("\n" ) ;
syntax. So, in
} general use this
one
56
Output of the code in the last slide
57
main( )
Accessing 2D array using pointer
{
Let’s see how this display function works
int a[3][4] = {
1, 2, 3, 4, - *q is receiving the address of a[0][0]. It
5, 6, 7, 8, has no idea about 2D array.
9, 0, 1, 6
} ; - We will use this loop to go to
display ( a, 3, 4 ) ; different rows and columns.
print ( a, 3, 4 ) ; - i will track row number and j will
}
track column number
display ( int *q, int row, int col )
{ - We will use this formula to access a
int i, j ; particular item in our 2D array:
for ( i = 0 ; i < row ; i++ )
{ - q+i*col+j //here col is the total
for ( j = 0 ; j < col ; j++ ) number of columns in the array
printf("%d ",*(q+i*col+j));
printf ( "\n" ) ;
- But how?:
}
printf ("\n" ) ; - See, q is always pointing to the first
} address of the array. It is not moving.
- Adding i*col will help to jump i*col
number of items. (kind of ith row)
- Then, adding j will help you to navigate
different items in that particular row 58
main( )
Accessing 2D array using pointer
{ i*4 is helping Let’s see how the display function works
int a[3][4] = { us to jump to - When, i = 0 (dealing with row 0):
1, 2, 3, 4,
5, 6, 7, 8,
ith row. (skip 4 - j = 0:
9, 0, 1, 6 numbers in each - *(q+ 0*4 + 0) = *(q+0) = 1
} ; row)
- j=1:
display ( a, 3, 4 ) ; - *(q+0*4 +1) = *(q+1) = 2
print ( a, 3, 4 ) ; - j=2:
} - *(q+0*4 +2) = *(q+2) = 3
display ( int *q, int row, int col )
- j=3:
{ - *(q+0*4 +3) = *(q+1) = 4
int i, j ;
for ( i = 0 ; i < row ; i++ ) - When, i = 1 (dealing with row 1):
{
for ( j = 0 ; j < col ; j++ ) - j = 0:
printf("%d ",*(q+i*col+j)); - *(q+ 1*4 + 0) = *(q+4) = 5
printf ( "\n" ) ; - j=1:
}
- *(q+1*4 +1) = *(q+5) = 6
printf ("\n" ) ;
} - j=2:
- *(q+1*4 +2) = *(q+6) = 7
- j=3:
- *(q+1*4 +3) = *(q+7) = 8
- Try for i = 2!
59
Strings
60
Strings review
• String is a char array
• Sequence of zero or more characters
terminated by null (‘\0’) character
• Note that ‘\0’ terminates the string but it is
not part of the string.
• strlen() function returns the length of a string.
null is not part of the length
• there are many useful functions for strings
are available at string.h
61
Strings review
• char s[10] = “cat”;
• Here s is an string and 10 bytes are allocated for the
string or array.
0 1 2 3 4 5 6 7 8 9
c a t ‘\0’
Output:
Enter name: Nusair Ahmed
Name: Nusair Ahmed
64
Alternative of gets() method for string input
• gets() method is dangerous as it does not care about the
size of the char array and can takes more than the size.
As a result your program can crash and become unsafe.
• Alternative:
char name[30];
printf("Enter name: ");
scanf("%[^\n]s",name);
• you can also use: fgets(name, sizeof(name),
stdin);
• In case of fgets, it also keep the ‘\n’ in the string. The following
line will remove that ‘\n’
• name[strcspn(name, "\n")] = 0;
• See uploaded example code: fgets_DifferentScanf.c
• You will also get explanation in the code 65
Problems with getting string input after another input
int main()
{
int id;
char name[30];
char ch, c;
while(1){
printf("\nMenu, e: enter, x: exit: ");
scanf("%c",&ch);
if(ch=='x’){
printf("\n<<<<<<<EXIT>>>>>>\n\n\n");
break;
}
if(ch=='e'){
printf("\nEnter student id: ");
scanf("%d",&id);
printf("\nEnter student name: ");
scanf("%[^\n]s",name);
printf("Your entered %d %s", id, name);
}
}
return 0;
} 66
Problems with getting string input after another input
• In the example shown at previous slide, the
string input after the integer input will be
skipped.
– The reason is when you press the enter key after
providing an integer input, the enter key is passed
to the next string input and the console does not
wait to take an string input as it already found the
input.
– To avoid this types of problem, use the following
loop before the string input and after other scanf:
– while ((c = getchar()) != '\n' && c != EOF); //you should
declare c before using it
– See example code in the next slide 67
int main()
{
int id;
char name[30];
char ch, c;
while(1){
printf("\nMenu, e: enter, x: exit: ");
scanf("%c",&ch);
if(ch=='x'){
printf("\n<<<<<<<EXIT>>>>>>\n\n\n");
break;
}
if(ch=='e'){
printf("\nEnter student id: ");
scanf("%d",&id);
printf("\nEnter student name: ");
while ((c = getchar()) != '\n' && c != EOF); //added this to eat the \n
scanf("%[^\n]s",name);
printf("Your entered %d %s", id, name);
while ((c = getchar()) != '\n' && c != EOF); //added this to eat the \n
for next input
}
}
return 0;
}
68
Some useful methods for string available in string.h (you will
need them very often in this semester)
• char *strcpy(char *dst, char const *src);
– It copies src string to the dst string
– It is programmers responsibility to ensure dst has enough space to copy from src.
• char *strcat(char *dest, const char *src)
– It takes two arguments, i.e, two strings or character arrays, and stores the resultant
concatenated string in the first string specified in the argument.
• size_t strlen(const char *str);
– Get the length of the passed string
• char *strstr(const char *haystack, const char *needle)
– Search for needle string inside haystack string and returns a pointer to the first occurrence in
haystack. Or a null pointer will be returned if needle is not found in haystack.
• int strcmp(char const *s1, char const *s2);
– Compares two strings. See the following table to understand he returned date
negative if the ASCII value of first unmatched character is less than second.
positive integer if the ASCII value of first unmatched character is greater than second.
69
int main()
{
strcmp test
char str1[] = "abcd", str2[] = "abde", str3[]="abCd",
str4[]="abcd";
int result;
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
71
Struct review
• When the data you want to store doesn't fit neatly into a predefined C
type, you can create your own. Here is an example:
struct employee {
char[20] name;
double salary;
int empID;
};
officeworker.empID = 1;
72
Struct and Pointer
• Structure is used to group related variables (members) of
various types together in an organized way. Also, we call it
custom data type.
struct employee {
char[20] name;
double salary;
int empID;
};
• Now, to declare a variable of this declared type, we write:
struct employee officeworker;
• Often times, for efficiency purposes, it's easier to declare pointers to structs and use those to manipulate
the structures formed.
• Consider the following:
struct employee *temp;// declare a pointer of type employee
temp = &officeworker; //store the address of office worker to temp
(*temp).salary = 50000; //dereference temp to access salary of officeworker
• Since expressions similar to the last one are used so often, there is a shorthand to access a field/member of
a record through a pointer to that record. The last statement can also be written as:
temp->salary = 50000 // -> is mostly used to dereference structure pointer.
• Another reason to use a pointer to a struct is to dynamically allocate the memory for the struct. (We will
briefly discuss about dynamic memory allocation in our next class).
• This allows the memory to be allocated beyond the “life”/”scope” of the function within which it was
declared.
73
Typedef and Pointers and Structures
temp
typedef struct bookRec{
float price;
char name[7];
}Book;
//if you use typedef, you don’t have to write struct
every time when you declare a variable of your
structure
aPtr
temp
struct bookRec{
float price;
char name[7];
}Book;
Book *aPtr;
Book temp;
aPtr = &temp;
75
Structures and Functions
• Example 1: Passing individual structure members
struct book{
char title[40];
char author[40]; This parameter list has no
int price; idea about the structure. It
}; can just take two char
void display(char *t, char *a, int p) pointers and one int
{
printf(“\n%s %s %d”,t, a, p);
}
main(){
struct book b1={“Programming knights”,”Arup
Guha”,50};
Here, we are passing our
display(b1); structure variable.
} Note: we are not passing
reerence
Passing reference to a structure in function
struct book{
char title[40];
char author[40];
int price; This function takes address
}; of a book structure variable.
This function has the ability
to change the value of b1.
void display(struct book *b)
{
printf(“\n%s %s %d”,b->title,b->author,b->price);
}
main(){
struct book b1={“Programming knights”,”Arup
Guha”,50};
Here, we are passing our
display(&b1); structure variable.
} Note: we are not passing
reerence
Returning a structure from a function
struct point{
int x;
int y; This function returns a point
type data
};
main(){
struct point p1, p2;
p1 = get();//calling get() function and storing the result in p1
p2 = get();
}
Array of Structures
• Let’s consider a case where we want to store data of
100 books. We would be required to use 100
different structure variables from b1 to b100, which
is definitely not very convenient.
• A better approach would be to use an array of
structures. books[0] title, author, price, pages
• Example: books[1] title, author, price, pages
typedef struct Book { books[2] title, author, price, pages
char title[50];
books[3] title, author, price, pages
char author[50];
float price; ……
int pages;
……
}Book;
Books[99] title, author, price, pages
Book books[100];
83
Source Codes
• All the codes in the slides as well as more
examples are available in creview folder in
webcourses.
84