Chapter 2. Arrays and Structures
Chapter 2. Arrays and Structures
Example 2: return 0;
}
a = 9;
b = &a; a = a + 1; // What is the effect on *b?
*b = 15; // What is the value kept in a?
Arrays and Structures 2-5
Array
An array is used to group the same objects
together.
Good things: If you know the index (where), you can find
the object (content) in one step.
Bad things: If you want to insert an object in
a place between two objects in an
array, you have to move the objects
first.
Array as an ADT
Array plus operations
associate with it.
Let the size of the array be n. The first element and the last
element are indexed by 0 and n-1, respectively.
Let the base address of an array to be a. The address of the i-th
element is located at a+(i-1) x sizeof(theTypeOfElement).
Example of Usages:
ptr[0] = &list[0]; ptr[1] = &list[2]; list[3] = list[2];
ptr[0] = list; ptr[1] = list + 2; list[3] = *ptr[1];
A[1][0][2]
A[2][1][2]
The address of A[0][0][1] is a+0*3*3+0*3+1=a+1
The address of A[1][0][2] is a+1*3*3+0*3+2=a+11
The address of A[2][1][2] is a+2*3*3+1*3+2=a+23
Arrays and Structures 2-15
Overview of Structures in C
Grouping data of different/same types.
Declare as user-defined data types:
typedef struct { typedef struct { typedef struct {
int day; char name[16]; char name[16];
int month; int student_id; int student_id;
int year; float mark; float mark;
} date; char grade; char grade;
date dob; date *dob;
} student; } studentp;
Some usages: (Note, there are “.” and “->”)
student s1, s2;
studentp p1, p2; Both “.” and “->” are to
date dob; access a data field defined
s1.dob.year = 1979;
strcpy(s1.name, "Mr.Right"); in a data structure.
p1.dob = &dob; “.” is to access a data field
p2.dob = &dob;
p1.dob->year = 1979; in a variable.
“->” is to access a data field
in a pointer.
Arrays and Structures 2-16
Self-Referential Structures
#define NULL 0
typedef struct _list {
int i;
struct _list *link;
} list;
int main()
{
list item1, item2, item3, *itemVar;
item1.i = 10; item2.i = 20; item3.i = 30;
item1.link = &item2; item2.link = &item3;
item3.link = NULL; itemVar = &item1;
while (itemVar != NULL) {
printf("%d\n", itemVar->i);
itemVar = itemVar->link;
}
return 0;
}
Arrays and Structures 2-17
Array as an ADT
i= 0 1 2 3 98 99 100
2 0 0 0 ... 0 0 1
i= 0 1 2 3 96 97 98 99 100
0 0 0 0 ... 1 9 3 0 1
typedef struct {
int degree;
float *coef;
} polynomial;
polynomial p1;
p1.degree = n;
p1.coef = (float*)malloc((p1.degree+1) *sizeof(float));
i= 0 1 2 3 98 99 100
2 0 0 0 ... 0 0 1
i= 0 1 2 3 4
1 9 3 0 1
typedef struct {
int start;
int finish;
} polynomial;
A polynomialbuffer to keep many.
0 1 2 3 4 5 6
global 100 0 4 3 2 0 expon
2 1 1 9 3 1 coef
typedef struct {
int number; /* the number of terms */
term *terms;
} polynomial;
polynomial p;
p.number = m;
p.terms = (term*)malloc(p.number * sizeof(term));
p.number 2
expon 100 0
p.terms
coef 2 1
p.number 4
expon 4 3 2 0
p.terms
coef 1 9 3 1