Chap1 Array Pointer Struct
Chap1 Array Pointer Struct
CODE TO TEAMS:
wg3m1hr
1
31/03/2022
Introduction
• C Programming practice in UNIX environment.
• Programming topics related to [Data Structures and Algorithms]
• Compiler: gcc
• Editor: Emacs, K-Developer,..
gcc syntax
• Parameter:
-Wall : turn on all alerts
-c: make object file
-o: name of output file
-g: debug information
-l: library
Example:
gcc –Wall hello.c –o runhello
./runhello
2
31/03/2022
Course outline
Chapter 1. Basic data types, I/O with files
Chapter 2. Recursion
Chapter 3. Lists
Chapter 4. Stack and Queue
Chapter 5. Trees
Chapter 6. Sorting
Chapter 7. Searching
3
31/03/2022
Contents
1. Pointers and arrays
2. String
3. Struct data type
4. Dynamic allocation
5. Input/output with text files
6. Input/output with binary files
Contents
1. Pointers and arrays
2. String
3. Struct data type
4. Dynamic allocation
5. Input/output with text files
6. Input/output with binary files
4
31/03/2022
5
31/03/2022
12
6
31/03/2022
7
31/03/2022
• There are many types of variables with different sizes, so there are
also many types of pointers. (Example: int pointer to point to a
variable or function of type int).
Example:
int *countPtr; //This is read as “countPtr is a pointer to an int”
double *tPtr; //This is read as “tPtr is a pointer to a double”
• A Pointer may be initialized to 0, NULL, or an address.
• A Pointer that is assigned 0 or NULL points to nothing.
16
8
31/03/2022
...
...
//or int * ptr;
ptr = &x; //assign ptr the memory address of x
ptr 345 3
346
Address of x is value of ptr 347
Dereference a pointer
• To declare pointer: type *pointer_name;
• Assign value to pointer (get address of other object and assign this address to
the pointer): pointer_name = &var_name;
(type of pointer_name and var_name must be the same)
• Access the object that the pointer points to: *pointer_name
(dereference the pointer)
Example:
double foo = 3.2;
double *ptr; ptr =&foo; //double *ptr = &foo;
printf(“%f”,*ptr); // this prints 3.2
• A pointer must have a value before you can dereference it (follow the pointer).
18
9
31/03/2022
Example: Pointer
int c;
int *ptr; /* declare ptr as an int pointer */
c = 7;
ptr = &c;
C
… 7 3 4 …
Address 172 173 174 175 176 177 178 179 180 181
ptr
… 174 3 4 …
Address 832 833 834 835 836 837 838 839 840 841
19
Pointers to anything
x some int
int *x;
int **y;
y some *int some int
double *z;
z some double
10
31/03/2022
11
31/03/2022
Example:
• to create an array scores having 9 elements
of integer type (4 bytes for each element)
• index starts at 0
24
12
31/03/2022
1D Array: initialization
• Arrays can be initialized with an initialization list:
#include <stdio.h>
int main(void){
int i, A[10];
return 0;
}
26
13
31/03/2022
Exercise 1 (Continue)
Write a program:
• Print on the screen the maximum value of these 10 integer numbers
• Print on the screen the minimum value of these 10 integer numbers
• Print on the screen the average value of these 10 integer numbers
Exercise 2
• Write a program that gets an input line from the user (ends with ‘\n’)
and displays the number of times each letter appears in it.
#define ALPHABET_LEN 26
int count[ALPHABET_LEN] = {0};
14
31/03/2022
int getchar(void)
int putchar(int char)
29
Exercise 2: Solution
#define ALPHABET_LEN 26
int main(void){
int i, count[ALPHABET_LEN] = {0};
char c = '\0';
printf("Please enter a line of text: \n");
/* Read in letter by letter and update the count array */
c = getchar();
while (c != '\n'){
if (c <= 'z' && c >= 'a') ++count[c - 'a’];
c = getchar();
}
for (i = 0; i < ALPHABET_LEN; ++i) {
if (count[i] > 0)
printf("The letter '%c' appears %d time(s).\n", 'a' + i, count[i]);
}
return 0;
}
15
31/03/2022
Exercise 3
• Implement a function that accepts two integer arrays of same size and returns 1 if
they are identical, 0 otherwise
– int compare_arrays(int arr1[], int arr2[], int size)
• Write a program that asks user to enter two integer arrays of same size and checks
for the identical by using the above function compare_arrays
arr1 1 2 3 4 5
arr1[0] arr1[1] arr1[2] arr1[3] arr1[4]
size=5
arr2 1 2 3 9 5
arr2[0] arr2[1] arr2[2] arr2[3] arr2[4]
32
16
31/03/2022
Rows of a 2D Array
17
31/03/2022
Columns of a 2D Array
2D array: Initialization
int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
int a[3][4] = {{1,2,3,4},{5,6,7,8}, {9,10,11,12}};
the 2nd method is more readable, because you can visualize the rows and columns of 2D array in this method
18
31/03/2022
2D array: Initialization
Example:
const int ROWS = 4, COLS = 3;
int exams[ROWS] [COLS];
int exams[ROWS] [COLS] = { {1,2,5},
{3,4,5},
{6,7,8},
{9,1,1}
};
int exams[ROWS] [COLS] = { {1,2}, {3,4} };
19
31/03/2022
20
31/03/2022
Pointer in expressions
• Integer math operations can be used with pointers.
• If you increase a pointer, it will be increased by the size of whatever it
points to.
ptr ~ address of a[0]
int a[5]; ptr+i ~ address of a[i]
int *ptr = a; Value of a[i]~ a[i]
~ ???? *(ptr+i)
Example
Write C program to print address and value of each element in a 1D-array:
#include <stdio.h>
int main()
{ Result in DevC
int A[ ] = {5, 10, 12, 15, 4}; (sizeof(int)=4)
printf("Address Contents\n“);
for (int i=0; i < 5; i++)
printf(“%d %d \n”,&A[i],A[i]);
return 0;
}
21
31/03/2022
Example
Write C program to print address and value of each element in a 1D-array:
#include <stdio.h>
int main()
{ int A[ ] = {5, 10, 12, 15, 4};
printf("Address Contents\n");
for (int i=0; i < 5; i++)
&A[i] : address of element A[i]
printf("%8d %5d\n", &A[i], A[i]); A[i] : value of element A[i]
printf("Address Contents\n");
for (int i=0; i < 5; i++) A+i : address of element A[i]
printf("%8d %5d\n", A+i, *(A+i)); *(A+i) : value of element A[i]
22
31/03/2022
Example
Write program in C to print address of elements in two-dimensional array:
#include <stdio.h>
Result in DevC
int main()
{ int a[4] [3] = {1,2,3,4,5,6,7,8,9,10,11,12};
(sizeof(int)=4)
printf("Address Contents\n");
for (int i=0; i < 4; i++)
for (int j=0; j < 3; j++)
printf("%8d %5d\n", &a[i][j], a[i][j]);
}
Location(a[1][2]) = ?
start_address=6487488
23
31/03/2022
24
31/03/2022
#include <stdio.h>
const int MAX = 100;
int main()
{
int numbers[MAX]; // Array of integers
int SIZE; // Size of the array
int count; // Counter variable
return 0; 49
}
25
31/03/2022
26
31/03/2022
Function parameter
(in its memory allocation)
x= value of v1 = 2;
y= value of v2 =3
Original argument
(in its memory allocation)
v1 = 2; v2 =3
54
27
31/03/2022
55
0x70fe0c 0x8123f3
v1 = 2 v2 = 3
28
31/03/2022
0x70fe0c 0x8123f3
v1 = 2 v2 = 3
Before swapping: v1 = 2, v2 = 3
v1 = 2 x =2 y =3 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
29
31/03/2022
v1 = 2 x =2 tmp = 2 y =3 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
v1 = 2 x =2 tmp = 2 y =3 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
30
31/03/2022
v1 = 2 x =3 tmp = 2 y =3 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
v1 = 2 x =3 tmp = 2 y =3 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
31
31/03/2022
v1 = 2 x =3 tmp = 2 y =2 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
v1 = 2 x =3 tmp = 2 y =2 v2 = 3
Function parameter
(in its memory allocation)
x= 2;
y= 3;
Before swapping: v1 = 2, v2 = 3
After swapping: v1 = 3, v2 = 2
32
31/03/2022
0x70fe0c 0x8123f3
v1 = 2 v2 = 3
65
0x70fe0c 0x8123f3
v1 = 2 v2 = 3
Before swapping: v1 = 2, v2 = 3
66
33
31/03/2022
v1 = 2 x = 0x70fe0c y = 0x8123f3 v2 = 3
Function parameter
(in its memory allocation)
x= 0x70fe0c;
y= 0x8123f3 ;
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
67
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
68
34
31/03/2022
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
69
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
70
35
31/03/2022
Function parameter
(in its memory allocation)
x= 0x70fe0c;
y= 0x8123f3 ;
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
71
Function parameter
(in its memory allocation)
x= 0x70fe0c;
y= 0x8123f3 ;
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
36
31/03/2022
Function parameter
(in its memory allocation)
x= 0x70fe0c;
y= 0x8123f3 ;
Address of v1 and v2
are sent to the
function swap, and
assigned to x and y
respectively
Before swapping: v1 = 2, v2 = 3
73
After swapping: v1 = 3, v2 = 2
37
31/03/2022
Exercise 5
• Write a function that accepts a double parameter and returns its
integer and fraction parts.
• Write a program that accepts a number from the user and prints out
its integer and fraction parts, using this function.
76
38
31/03/2022
#include <stdio.h>
39
31/03/2022
Printing an array
void print_array(int a[], int len) {
for (i=0;i<len;i++)
printf(“a[%d] = %d \n“,i,a[i]);
}
Printing an array
80
40
31/03/2022
Exercise 6
Write a program that includes the following functions:
Input values for an array
Increase all values of the array by 2
Print out an array
You should use pointers to access the array. The array is
passed as function parameters
Array version:
void input_array(int a[], int len);
void change_array(int a[], int len);
void print_array(int a[], int len);
Pointer version:
void input_arrayP(int *a, int len);
void change_arrayP(int *a, int len);
void print_arrayP(int *a, int len);
81
82
41
31/03/2022
83
84
42
31/03/2022
Two-Dimensional Arrays
• Passing two-dimensional array to functions: use empty [] for row, size
declarator for column in prototype, header:
const int COLS = 2;
void getExams(int [] [COLS], int); // prototype
void getExams(int exams [] [COLS], int rows); // header
Exercise 7
Write a program to
• get the size of a matrix : row, col
• Get the elements of two matrices with that size: Arow*col and Brow*col
• Calculate the addition of two matrices
43
31/03/2022
Exercise
87
Exercise 8
Write a program to
• get the size of a matrix : row, col
• Get the elements of two matrices with that size: Arow*col and Brow*col
• Calculate the addition of two matrices
44
31/03/2022
Exercise 8
89
Exercise 8
45
31/03/2022
Homework 1
Write:
1) Function int countNum(int n) returns the total of all
numbers in the range [1, n] that satisfy one of the two
following conditions:
a. Both divisible for 3 and 5
b. Divide by 3 remainder 2, divide by 5 remainder 3
2) A program to get an integer n≥1, then call the function
countNum above to get the result.
Homework 2
Write a program to get an integer n ≥ 2 and two square matrix
An*n and Bn*n; then calculate A*B.
Note: Using two-dimensional array to store the square matrix
46
31/03/2022
Contents
1. Pointers and arrays
2. String
3. Struct data type
4. Dynamic allocation
5. Input/output with text files
6. Input/output with binary files
2. String
• An array of characters.
• You can initialize strings in a number of ways:
Terminator
47
31/03/2022
Note :
gets() has been removed from c11. So it might give you a warning when
implemented.
We see here that it doesn’t bother about the size of the array. So, there is a
chance of Buffer Overflow.
48
31/03/2022
49
31/03/2022
50
31/03/2022
Exercise 9
• Write a function that:
– gets a string and two chars
– the functions scans the string and replaces every occurrence of the
first char with the second one.
void replace(char str[], char replace_what, char replace_with)
• Write a program to test the above function
– the program gets from the keyboard a string (no spaces) and two
characters, then calls the function with the input, and prints the
result on screen.
Example
– input: “papa”, ‘p’, ‘m’
– output: “mama”
51
31/03/2022
Exercise 10
• Write a function with the prototype:
void replace_char(char *str, char c1, char c2);
• It replaces each appearance of c1 by c2 in the string str.
• Demonstrate your function with a program that uses it
Contents
1. Pointers and arrays
2. String
3. Struct data type
4. Dynamic allocation
5. Input/output with text files
6. Input/output with binary files
52
31/03/2022
3. Struct
• Example:
struct {
int numerator;
int denominator;
} fraction;
[Link] = 13;
[Link] = 17;
106
53
31/03/2022
107
Figure 1. Array of records
Method 1 Method 2
Without using typdef Using typdef
54