CSC 2400: Computer Systems Arrays and Strings in C

CSC 2400: Computer Systems

Arrays and Strings in C

Lecture Overview

? Arrays

! List of elements of the same type

? Strings

! Array of characters ending in `\0' ! Functions for manipulating strings

1

Arrays in C

int a[5]; a

Label Address

217

a[0] 400

a[1] 404

a[2] 408

226

a[3] 412

a[4] 416

What is "a" in the picture above?

a is the address of the first array element a[0]

- not five consecutive array elements - we will see that a is a constant pointer (covered in next lecture)

Array Indices

? Logically, valid indices for an array range from 0 to MAX-1, where MAX is the dimension of the array

int a[6]; stands for a[0], a[1], a[2], a[3], a[4] and a[5] Logically, there is no a[6]!

? Memory

a[0] a[1] a[2] a[3] a[4] a[5]

2

Arrays: C vs. Java

Arrays

Array bound checking

Java

int [] a = new int [10]; float [][] b =

new float [5][20];

// run-time check

C

int a[10]; float b[5][20];

/* no run-time check */

C Does Not Do Bounds Checking!

int a[5]; a

a[0] = 217; a[3] = 226;

55

Label Address

217

a[0] 400

a[1] 404

a[2] 408

226

a[3] 412

a[4] 416

a[-1] = 55; 320

a[7] = 320;

Unpleasant if you happened to have another variable before the array variable a, or after it!

3

Example Program: Reverse Array

? Reverse the values in an array

! Inputs: integer array a, and number of elements n ! Output: values of a stored in reverse order

? Algorithm

! Swap the first and last elements in the array ! Swap the second and second-to-last elements ! ...

77 31 94 5 186

Example of Array Code

void reverse (int a[], int n) { int l, r, temp; for (l=0, r=n-1; l ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download