SC, Chen
Ch8 Arrays
Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch8 Arrays
8.1 One-Dimensional Arrays
8.2 Multidimensional Arrays
8.3 Variable-Length Arrays (C99)
• Scalar: Be capable of holding a single data item
• Aggregate variables: Can store collections of values
1. Arrays
2. Structure Structures
ch16
8.1 One-Dimensional Arrays
• Array
A data structure containing a number of data values, all of which have the same type
Elements
− Data values
− Can be individually selected by their position within the array
Simplest kind of array: One-dimensional array
− The elements of a one-dimensional array are conceptually arranged one after another in a single row
• Declaring an array
Specify the type of the array’s elements
− May be any type
Specify the number of elements
− Can be specified by any (integer) constant expression
− Using a macro to define the length of an array which the array lengths may need to be adjusted when
the program is later changed is good
Constant
expressions
Ch5.3
int a[10]; /* Array a with 10 int elements */
8.1 One-Dimensional Arrays: Array Subscripting
(1/2)
• Subscripting or Indexing
To access a particular element of an array, write the array name followed by
integer value in square brackets
The number of array element starts from 0 (0 to n-1)
Expressions of the form a[i] are lvalues
− Can be used in the same way as ordinary variables
• Each element of the array is the same data type
• Arrays and for loops go hand-in-hand
lvalues
Ch4.2
for ( i = 0; i < N; i++)
a[i] = 0; /* clears a */
for ( i = 0; i < N; i++)
scanf(“%d”, &a[i]); /* reads data into a */
for ( i = 0; i < N; i++)
sum += a[i]; /* sums the elements of a */
Array Subscripting
• Why starts at 0 instead of 1?
A pointer(array) is a memory direction and index is an offset of that memory
direction, so the first element of the pointer(array) is the one who offset is equal to 0
• What if I want an array with subscripts that go from 1 to 10 instead of 0 to 9?
A common trick that declare the array to have 11 elements instead of 10
• Use a character as an array subscript
Using ASCII for example
1. To scale a lower-case letter
− Subtract ‘a’
2. To scale an upper-case letter
− Subtract ‘A’
Is not completely portable since letters may not be consecutive codes
8.1 One-Dimensional Arrays: Array Subscripting
(2/2)
• An array subscript may be any integer expression
There may have side effects
C doesn’t require that subscript bounds be checked
 If a subscript goes out of range: The program’s behavior is undefined
 Cause:
− Forgetting that an array with n elements is indexed from 0 to n-1
for ( i = 1; i <= 10; i++)
a[i] = 0;
• There may be an infinite loop
• When i reaches 10, but a[10] doesn’t exit
• 0 goes into memory after a[9]
• If the variable i happens to follow a[9] in memory
a[i + j * 10] = 0;
i = 0;
while (i < N)
a[i++] = 0;
for ( i = 0; i < N; i++)
a[i] = b[i];
i = 0;
while (i < N)
a[i] = b[i++];
The expression a[i] = b[i++] accesses the value
of i and also modifies i elsewhere in the
expression will cause undefined behavior
8.1 One-Dimensional Arrays: Reversing a Aeries
of Numbers
8.1 One-Dimensional Arrays: Array Initialization
• The rules of array initialization are somewhat tricky
• The most common form of array initializer is a list of constant
expression enclosed in braces and separated by commas
initializer
Ch18.5
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int b[10] = {1, 2, 3, 4, 5}; /* initial value of b is {1, 2, 3, 4, 5, 0, 0, 0, 0, 0};*/
int c[10] = {0}; /* initial value of c is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};*/
int d[10] = { }; /* illegal */
int e[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; /* illegal */
int f[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* If an initializer is present, the length of the array may be omitted */
8.1 One-Dimensional Arrays: Designated Initializers
• Designated Initializers in C99
Can initialize an array with just some of the elements to be initialized explicitly
Each number in brackets is said to be a designator
Shorter and easier to read for some arrays
The order in which the elements are listed no longer matters
Must be integer constant expressions
• If the array being initialized with length n
Each designator must be between 0 and n-1
• If the array begin initialized with length omitted
A designator can be any nonnegative integer
The compiler will deduce the length of the array from the largest designator
• An initializer can use both the element-by-element and the designated technique
C99
int a[15] = {[14] = 29, [9] = 7, [2] = 48};
int b[ ] = {[14] = 29, [9] = 7, [2] = 48};
int c[15] = {0, 48, [14] = 29, [9] = 7};
8.1 One-Dimensional Arrays: Checking a Number
for Repeated Digits
int a[ ] = {4 ,9, 1, 8, [0] = 5, 7};
int a[ ] = {5 ,7, 1, 8};
8.1 One-Dimensional Arrays: Using the sizeof
Operator with Arrays
• sizeof
1. Can determine the size of an array in bytes
2. Can measure the size of an array element
Dividing the array size by the element size gives the length of the array
The loop doesn’t have to be modified if the array length should change at a later date
with this
− Also can use a macro definition, but sizeof is a little bit better
Some compiler produce a warning message for this expression
− Can add a cast to avoid this warning
int a[10] = {0}; /* sizeof(a) is 10*4 = 40 bytes*/
sizeof(a) / sizeof(a[0])
for ( i = 0; (int) i < sizeof(a) / sizeof(a[0]); i++)
a[i] = 0;
int (signed type) size_t (unsigned type)
#define SIZE (int) i < sizeof(a) / sizeof(a[0])
parameter
macros
Ch14.3
What’s the advantage of sizeof
comparing with using a macro?
8.1 One-Dimensional Arrays: Computing Interest
Copy Array
• Cannot copy one array into another by using the assignment operator
C and C++ don’t provide an array type
− Arrays are simply an area of contiguous allocated memory
− The name of the array is actually a pointer to the first element of the array
• Solution?
1. Using a loop that copies the elements
2. Using the memcpy (memory copy) function from the <string.h> header
A low-level function that simply copies bytes from one place to another memcpy
function
Ch23.6
for ( i = 0; i < N; i++)
a[i] = b[i];
a = b; /* a and b are arrays */
memcpy(a, b, sizeof(a));
8.2 Multidimensional Arrays
• An array may have any number of dimensions
A two-dimensional array: matrix
− type m[x][y]: An array m with x rows and y columns
− Use m[i][j] to access the element of m in row i, column j
• C stores arrays in row-major order
• Nested for loops are ideal for processing multidimensional arrays
• C provides a more flexible way to store multidimensional data
Arrays of pointers
comma
operator
Ch6.3
Don’t use m[i, j]
• C treats the comma as an operator in this context
• Is the same as m[j]
Row 0 Row 2 … Row i-1
m[0, 0] … m[0, j-1] m[1, 0] … m[1, j-1] … m[i-1, 0] … m[i-1, j-1]
arrays of
pointers
Ch13.7
8.2 Multidimensional Arrays: Initializing a
Multidimensional Arrays
• Initialize a nesting one-dimensional initializers for a two-dimensional array
Each inner initializer provides values for one row of the matrix
Initializers for higher-dimensional arrays are constructed in a similar fashion
• C provides a variety of ways to abbreviate initializers for multidimensional arrays
1. If an initializer isn’t large enough to fill a multidimensional array
 The remaining elements are given the value 0
2. If an inner list isn’t long enough to fill a row
 The remaining elements in the row are initialized to 0
3. Can even omit the inner braces
• C99’s designated initializers work with multidimensional arrays
int m[2][5] = {{0, 1, 2, 3, 4},
{4, 3, 2, 1, 0}};
double m[2][2] = {[0][0] = 1.0, [1][1] = 1.0};
C
8.2 Multidimensional Arrays: Constant Arrays
• Any array can be made “constant” by starting its declaration with the
word const
Should not be modified by the program later
The compiler will detect direct attempts to modify an element
It documents that the program won’t change the array
1. Be valuable information for someone reading the code later
2. Helps the compiler catch errors by informing it that we don’t intend to modify the array
• const isn’t limited to arrays
Works with any variable
const type
qualifier
Ch18.3
8.2 Multidimensional Arrays: Dealing a Hand of
Cards
8.3 Variable-Length Arrays (C99)
• Previous stated that the length of an array variable must be specified by a
constant expression
• It is possible to use an expression that’s not constant to state the length of an
array in C99: Variable-Length Arrays (VLA)
The length of VLA is computed when the program is executed
The length of VLA doesn’t have to be specified by a single variable
VLA also can be multidimensional
The programmer doesn’t have to pick an arbitrary length when declaring an array
− If the programmer makes the choice
1. The array will be too long (wasting memory)
2. The array will be too short (causing the program to fail)
Restrictions
1. VLA can’t have static storage duration
2. VLA may not have an initializer
VLAs are most often seen in functions other than main
VLA that belongs to a function f is that it can have a different length each time f is called
C99
static storage
duration
Ch18.2
VLA and goto
• The memory used to store a VLA is usually allocated when the declaration
of the array is reached during program execution
• Bypassing the declaration using a goto statement could result in a program
accessing the elements of an array that was never allocated

Ch8 Arrays

  • 1.
    SC, Chen Ch8 Arrays SelfStudy Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2.
    Ch8 Arrays 8.1 One-DimensionalArrays 8.2 Multidimensional Arrays 8.3 Variable-Length Arrays (C99) • Scalar: Be capable of holding a single data item • Aggregate variables: Can store collections of values 1. Arrays 2. Structure Structures ch16
  • 3.
    8.1 One-Dimensional Arrays •Array A data structure containing a number of data values, all of which have the same type Elements − Data values − Can be individually selected by their position within the array Simplest kind of array: One-dimensional array − The elements of a one-dimensional array are conceptually arranged one after another in a single row • Declaring an array Specify the type of the array’s elements − May be any type Specify the number of elements − Can be specified by any (integer) constant expression − Using a macro to define the length of an array which the array lengths may need to be adjusted when the program is later changed is good Constant expressions Ch5.3 int a[10]; /* Array a with 10 int elements */
  • 4.
    8.1 One-Dimensional Arrays:Array Subscripting (1/2) • Subscripting or Indexing To access a particular element of an array, write the array name followed by integer value in square brackets The number of array element starts from 0 (0 to n-1) Expressions of the form a[i] are lvalues − Can be used in the same way as ordinary variables • Each element of the array is the same data type • Arrays and for loops go hand-in-hand lvalues Ch4.2 for ( i = 0; i < N; i++) a[i] = 0; /* clears a */ for ( i = 0; i < N; i++) scanf(“%d”, &a[i]); /* reads data into a */ for ( i = 0; i < N; i++) sum += a[i]; /* sums the elements of a */
  • 5.
    Array Subscripting • Whystarts at 0 instead of 1? A pointer(array) is a memory direction and index is an offset of that memory direction, so the first element of the pointer(array) is the one who offset is equal to 0 • What if I want an array with subscripts that go from 1 to 10 instead of 0 to 9? A common trick that declare the array to have 11 elements instead of 10 • Use a character as an array subscript Using ASCII for example 1. To scale a lower-case letter − Subtract ‘a’ 2. To scale an upper-case letter − Subtract ‘A’ Is not completely portable since letters may not be consecutive codes
  • 6.
    8.1 One-Dimensional Arrays:Array Subscripting (2/2) • An array subscript may be any integer expression There may have side effects C doesn’t require that subscript bounds be checked  If a subscript goes out of range: The program’s behavior is undefined  Cause: − Forgetting that an array with n elements is indexed from 0 to n-1 for ( i = 1; i <= 10; i++) a[i] = 0; • There may be an infinite loop • When i reaches 10, but a[10] doesn’t exit • 0 goes into memory after a[9] • If the variable i happens to follow a[9] in memory a[i + j * 10] = 0; i = 0; while (i < N) a[i++] = 0; for ( i = 0; i < N; i++) a[i] = b[i]; i = 0; while (i < N) a[i] = b[i++]; The expression a[i] = b[i++] accesses the value of i and also modifies i elsewhere in the expression will cause undefined behavior
  • 7.
    8.1 One-Dimensional Arrays:Reversing a Aeries of Numbers
  • 8.
    8.1 One-Dimensional Arrays:Array Initialization • The rules of array initialization are somewhat tricky • The most common form of array initializer is a list of constant expression enclosed in braces and separated by commas initializer Ch18.5 int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int b[10] = {1, 2, 3, 4, 5}; /* initial value of b is {1, 2, 3, 4, 5, 0, 0, 0, 0, 0};*/ int c[10] = {0}; /* initial value of c is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};*/ int d[10] = { }; /* illegal */ int e[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; /* illegal */ int f[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* If an initializer is present, the length of the array may be omitted */
  • 9.
    8.1 One-Dimensional Arrays:Designated Initializers • Designated Initializers in C99 Can initialize an array with just some of the elements to be initialized explicitly Each number in brackets is said to be a designator Shorter and easier to read for some arrays The order in which the elements are listed no longer matters Must be integer constant expressions • If the array being initialized with length n Each designator must be between 0 and n-1 • If the array begin initialized with length omitted A designator can be any nonnegative integer The compiler will deduce the length of the array from the largest designator • An initializer can use both the element-by-element and the designated technique C99 int a[15] = {[14] = 29, [9] = 7, [2] = 48}; int b[ ] = {[14] = 29, [9] = 7, [2] = 48}; int c[15] = {0, 48, [14] = 29, [9] = 7};
  • 10.
    8.1 One-Dimensional Arrays:Checking a Number for Repeated Digits
  • 11.
    int a[ ]= {4 ,9, 1, 8, [0] = 5, 7}; int a[ ] = {5 ,7, 1, 8};
  • 12.
    8.1 One-Dimensional Arrays:Using the sizeof Operator with Arrays • sizeof 1. Can determine the size of an array in bytes 2. Can measure the size of an array element Dividing the array size by the element size gives the length of the array The loop doesn’t have to be modified if the array length should change at a later date with this − Also can use a macro definition, but sizeof is a little bit better Some compiler produce a warning message for this expression − Can add a cast to avoid this warning int a[10] = {0}; /* sizeof(a) is 10*4 = 40 bytes*/ sizeof(a) / sizeof(a[0]) for ( i = 0; (int) i < sizeof(a) / sizeof(a[0]); i++) a[i] = 0; int (signed type) size_t (unsigned type) #define SIZE (int) i < sizeof(a) / sizeof(a[0]) parameter macros Ch14.3 What’s the advantage of sizeof comparing with using a macro?
  • 13.
    8.1 One-Dimensional Arrays:Computing Interest
  • 14.
    Copy Array • Cannotcopy one array into another by using the assignment operator C and C++ don’t provide an array type − Arrays are simply an area of contiguous allocated memory − The name of the array is actually a pointer to the first element of the array • Solution? 1. Using a loop that copies the elements 2. Using the memcpy (memory copy) function from the <string.h> header A low-level function that simply copies bytes from one place to another memcpy function Ch23.6 for ( i = 0; i < N; i++) a[i] = b[i]; a = b; /* a and b are arrays */ memcpy(a, b, sizeof(a));
  • 15.
    8.2 Multidimensional Arrays •An array may have any number of dimensions A two-dimensional array: matrix − type m[x][y]: An array m with x rows and y columns − Use m[i][j] to access the element of m in row i, column j • C stores arrays in row-major order • Nested for loops are ideal for processing multidimensional arrays • C provides a more flexible way to store multidimensional data Arrays of pointers comma operator Ch6.3 Don’t use m[i, j] • C treats the comma as an operator in this context • Is the same as m[j] Row 0 Row 2 … Row i-1 m[0, 0] … m[0, j-1] m[1, 0] … m[1, j-1] … m[i-1, 0] … m[i-1, j-1] arrays of pointers Ch13.7
  • 16.
    8.2 Multidimensional Arrays:Initializing a Multidimensional Arrays • Initialize a nesting one-dimensional initializers for a two-dimensional array Each inner initializer provides values for one row of the matrix Initializers for higher-dimensional arrays are constructed in a similar fashion • C provides a variety of ways to abbreviate initializers for multidimensional arrays 1. If an initializer isn’t large enough to fill a multidimensional array  The remaining elements are given the value 0 2. If an inner list isn’t long enough to fill a row  The remaining elements in the row are initialized to 0 3. Can even omit the inner braces • C99’s designated initializers work with multidimensional arrays int m[2][5] = {{0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}}; double m[2][2] = {[0][0] = 1.0, [1][1] = 1.0}; C
  • 17.
    8.2 Multidimensional Arrays:Constant Arrays • Any array can be made “constant” by starting its declaration with the word const Should not be modified by the program later The compiler will detect direct attempts to modify an element It documents that the program won’t change the array 1. Be valuable information for someone reading the code later 2. Helps the compiler catch errors by informing it that we don’t intend to modify the array • const isn’t limited to arrays Works with any variable const type qualifier Ch18.3
  • 18.
    8.2 Multidimensional Arrays:Dealing a Hand of Cards
  • 19.
    8.3 Variable-Length Arrays(C99) • Previous stated that the length of an array variable must be specified by a constant expression • It is possible to use an expression that’s not constant to state the length of an array in C99: Variable-Length Arrays (VLA) The length of VLA is computed when the program is executed The length of VLA doesn’t have to be specified by a single variable VLA also can be multidimensional The programmer doesn’t have to pick an arbitrary length when declaring an array − If the programmer makes the choice 1. The array will be too long (wasting memory) 2. The array will be too short (causing the program to fail) Restrictions 1. VLA can’t have static storage duration 2. VLA may not have an initializer VLAs are most often seen in functions other than main VLA that belongs to a function f is that it can have a different length each time f is called C99 static storage duration Ch18.2
  • 20.
    VLA and goto •The memory used to store a VLA is usually allocated when the declaration of the array is reached during program execution • Bypassing the declaration using a goto statement could result in a program accessing the elements of an array that was never allocated

Editor's Notes

  • #15 The problem with C and C++ is that these languages do not provide an array type. Instead, arrays are simply an area of contiguous allocated memory and the name of the array is actually a pointer to the first element of the array. In languages with actual first class array types, such as Ada, an array can be copied using the assignment operator. Ada performs what C would call a memcopy. Of course, when performing such a copy the array, or the array slice receiving the data must be of the same type and length as the array or array slice sending the data.