You are on page 1of 46

Arrays in C & C

++
(including a brief introduction to pointers)
CS-2303 System Programming Concepts
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and from C: How to Program, 5th and 6th editions, by Deitel and Deitel)

CS-2303, C-Term 2010

Arrays in C & C++

1

Reading Assignment
• Chapter 6 of Deitel & Deitel • Chapter 5 of Kernighan & Ritchie

CS-2303, C-Term 2010

Arrays in C & C++

2

Definition – Array
• A collection of objects of the same type stored contiguously in memory under one name
• May be type of any kind of variable • May even be collection of arrays!

• For ease of access to any member of array • For passing to functions as a group
CS-2303, C-Term 2010 Arrays in C & C++ 3

Arrays in C
• By far, the dominant kind of data structure in C programs • Many, many uses of all kinds
• Collections of all kinds of data • Instant access to any element

CS-2303, C-Term 2010

Arrays in C & C++

4

Examples • int A[10] • An array of ten integers • A[0]. unions.. etc. C-Term 2010 Arrays in C & C++ 5 . …. pointers. A[9] • double B[20] • An array of twenty long floating point numbers • B[0]. A[1]. are also allowed • Array indexes always start at zero in C CS-2303. B[19] • Arrays of structs. …. B[1].

D[1][0]. …. D[0][1]. C-Term 2010 Arrays in C & C++ 6 . …. each of which is an array of twenty integers • D[0][0]. C[1]. D[1][1].Examples (continued) • int C[] • An array of an unknown number of integers (allowable in a parameter of a function) • C[0]. D[9][19] • Not used so often as arrays of pointers CS-2303. C[max-1] • int D[10][20] • An array of ten rows. ….

elements of last subscript are stored contiguously in memory • Also. int D[10][20] /*[row][col]*/ • Last subscript varies the fastest – I. C-Term 2010 Arrays in C & C++ 7 .Two-dimensional Arrays • int D[10][20] – A one-dimensional array with 10 elements.e... each of which is an array with 20 elements • I. three or more dimensions CS-2303.e.

CS-2303. x = y – A[3].Array Element • May be used wherever a variable of the same type may be used • In an expression (including arguments) • On left side of assignment • Examples:– A[3] = x + y. C-Term 2010 Arrays in C & C++ 8 . z = sin(A[i]) + cos(B[j]).

Array Elements (continued) • Generic form:– • ArrayName[integer-expression] • ArrayName[integer-expression] [integer-expression] – Same type as the underlying type of the array • Definition:– Array Index – the expression between the square brackets • Also called an Array Subscript CS-2303. C-Term 2010 Arrays in C & C++ 9 .

j++) sum += B[j].. for(sum = 0. i++) A[i] = i*i. j < max. &A[count]). for(i=0.g. j=0. for (count=0. i < max. CS-2303.rc!=EOF.Array Elements (continued) • Array elements are commonly used in loops • E. C-Term 2010 Arrays in C & C++ 10 .count++) rc=scanf("%f".

whether index points to an element within the array • Might be high (beyond the end) or negative (before the array starts) CS-2303. C-Term 2010 Arrays in C & C++ 11 .e..Caution! Caution! Caution! • It is the programmer’s responsibility to avoid indexing off the end of an array • Likely to corrupt data • May cause a segmentation fault • Could expose system to a security hole! • C does NOT check array bounds • I.

. whether index points to an element within the array • Might be high (beyond the end) or negative (before the array starts) CS-2303.Caution! Caution! Caution! • It is the programmer’s responsibility to avoid indexing off the end of an array • Likely to corrupt data • May cause a segmentation fault • Could expose system to a security hole! • C does NOT check array bounds • I.e. C-Term 2010 Arrays in C & C++ 12 .

Questions CS-2303. C-Term 2010 Arrays in C & C++ 13 .

Declaring Arrays • Static or automatic • Array size may be determined explicitly or implicitly • Array size may be determined at run-time • Automatic only • Not in textbook CS-2303. C-Term 2010 Arrays in C & C++ 14 .

C-Term 2010 Arrays in C & C++ /*not visible to 15 . #define CLASS_SIZE 73 double B[CLASS_SIZE]. const int nElements = 25 float C[nElements]. linker */ CS-2303.Declaring Arrays (continued) • Outside of any function – always static int A[13]. static char S[256].

static char D[256]. const int nElements = 25 float C[nElements].Declaring Arrays (continued) • Outside of any function – always static int A[13]. #define CLASS_SIZE 73 double B[CLASS_SIZE]. C-Term 2010 Arrays in C & C++ Static  retains values across function calls /*not visible to 16 . linker */ CS-2303.

C-Term 2010 Arrays in C & C++ 17 .Static Data Allocation 0xFFFFFFFF stack (dynamically allocated) SP address space heap (dynamically allocated) static data program code (text) PC 0x00000000 CS-2303.

static char D[256].Declaring Arrays (continued) • Inside function or compound statement – usually automatic void f( …) { int A[13]. not visible outside function */ } //f CS-2303. C-Term 2010 Arrays in C & C++ 18 . #define CLASS_SIZE 73 double B[CLASS_SIZE]. /*static. const int nElements = 25 float C[nElements].

C-Term 2010 Arrays in C & C++ 19 .Static Data Allocation 0xFFFFFFFF stack (dynamically allocated) SP address space heap (dynamically allocated) static data program code (text) PC 0x00000000 CS-2303.

Declaring Arrays (continued) • Inside function or compound statement – usually automatic void f( …) { int A[13]. static char D[256]. #define CLASS_SIZE 73 double B[CLASS_SIZE]. const int nElements = 25 float C[nElements]. not visible outside function */ } //f CS-2303. /*static. C-Term 2010 Arrays in C & C++ 20 .

e.Dynamic Array Size Determination • gcc supports the following:– void func(<other parameters>. array size is determined by evaluating an expression at run-time • Automatic allocation on The Stack • Not in C88 ANSI standard. const int n) { double Arr[2*n]. not in Kernighan & Ritchie • Part of C99 and C++ CS-2303. } //func • I. C-Term 2010 Arrays in C & C++ 21 ..

• gcc. 32}. 8. 4*n. C99. C-Term 2010 Arrays in C & C++ 22 . 4. all other elements initialized to 0 CS-2303. • Static or automatic • int B[20] = {2. 16. array initialized to expressions • int E[n] = {1}. 16. 32}. • Error — compiler detects too many initial values • int D[5] = {2*n. 4. 16*n. Zeroth element initialized to 1. 16. 4. 32*n}. • Automatically only. 32}. • Unspecified elements are guaranteed to be zero • int C[4] = {2. 8. 8.Array Initialization • int A[5] = {2. C++ • Dynamically allocated array (automatic only). 8*n.

86 of K&R CS-2303. 30. 31. C-Term 2010 Arrays in C & C++ 23 . 30. 12 elements – Values must be compile-time constants (for static arrays) – Values may be run-time expressions (for automatic arrays) – See p. – Array is created with as many elements as initial values • In this case. 31. 30. 31}. 30. 31.Implicit Array Size Determination • int days[] = {31. 31. 31. 28.

7 of D&D • Examples:– • sizeof (int) – # of bytes per int • sizeof (float) – # of bytes per float • sizeof days – # of bytes in array days (previous slide) • # of elements in days = (sizeof days)/sizeof(int) • Must be able to be determined at compile time • Getting size of dynamically allocated arrays not supported CS-2303.135 of K&R. §7.Getting Size of Implicit Array • sizeof operator – returns # of bytes of memory required by operand • See p. C-Term 2010 Arrays in C & C++ 24 .

C-Term 2010 Arrays in C & C++ 25 .135 • Examples:– • sizeof (int) – # of bytes per int • sizeof (float) – # of bytes per float • sizeof days – # of bytes in array days (previous slide) • # of elements in days = (sizeof days)/sizeof(int) • Must be able to be determined at compile time • Getting size of dynamically allocated arrays not supported CS-2303.Getting Size of Implicit Array • sizeof operator – returns # of bytes of memory required by operand • See p.

30. 31.28.28.31.31.31.30.31.30.31.31.30.31. {31. // daytab CS-2303.31}. // daytab OR static char daytab[2][12] = { 31.29.31.30. C-Term 2010 Arrays in C & C++ 26 .30.31 }.31.31.30.31.31.Initializing a Two-Dimensional Array static char daytab[2][12] = { {31.30.31.31.30.31.30.30.31} }.30.31.31.31.30.31.31.31.29.30.30.30.

C-Term 2010 Arrays in C & C++ 27 .Questions? CS-2303.

Digression – Memory Organization ∙∙∙ 0 1 2 3 4 5 6 7 8 9 10 11 2n-1 • All modern processors have memories organized as sequence of numbered bytes • Many (but not all) are linear sequences • Notable exception – Pentium! • Definitions:– – Byte: an 8-bit memory cell capable of storing a value in range 0 … 255 – Address: number by which a memory cell is identified CS-2303. C-Term 2010 Arrays in C & C++ 28 .

g.e.. • • • • • short int – 2 bytes int – 2 or 4 bytes long – 4 or 8 bytes float – 4 bytes double – 8 bytes • (Almost) always aligned to multiple of size in bytes • Address is ―first‖ byte of sequence (i.. C-Term 2010 Arrays in C & C++ 29 .Memory Organization (continued) ∙∙∙ 0 1 2 3 4 5 6 7 8 9 10 11 2n-1 • Larger data types are sequences of bytes – e. byte zero) • May be low-order or high-order byte • Big endian or Little endian CS-2303.

.g. 4.Definition – Pointer 11 0 1 2 3 4 5 6 7 8 9 10 11 ∙∙∙ 2n-1 • A value indicating the number of (the first byte of) a data object – Also called an Address or a Location • Used in machine language to identify which data to access • E. C-Term 2010 Arrays in C & C++ 30 . stack pointer is address of most recent entry of The Stack • Usually 2. or 8 bytes. depending upon machine architecture CS-2303.

Memory Addressing 0xFFFFFFFF stack (dynamically allocated) SP address space heap (dynamically allocated) static data program code (text) PC 0x00000000 CS-2303. C-Term 2010 Arrays in C & C++ 31 .

Pointers in C • Used everywhere – For building useful.g.e. &x). C-Term 2010 Arrays in C & C++ 32 .. *p = *q.. interesting.. scanf("%d".e. gets value pointed to – E. a legal object on left of assignment operator ('=') • Unary '*' operator dereferences a pointer – i.. – Operand of '&' must be an l-value — i.g. – E.g. data structures – For returning data from functions – For managing arrays • '&' unary operator generates a pointer to x – E.g. CS-2303. *p = x + y. p = &c.. *p refers to value of c (above) – E.

— a pointer to an object of type type • E. — a pointer to a pointer to a • int *p. CS-2303. etc. a struct. something defined by a typedef. function. — a pointer to a double • char **r. char • type *s.Declaring Pointers in C — a pointer to an int • double *q.g. union. C-Term 2010 Arrays in C & C++ 33 .

e.. pointer can change. thing it points to cannot • int * const q..e. • p is a pointer to an integer constant • I. • q is a constant pointer to an integer variable • I.Declaring Pointers in C (continued) • Pointer declarations:–read from right to left • const int *p. • r is a constant pointer to an integer constant CS-2303. pointer cannot change. C-Term 2010 Arrays in C & C++ 34 . thing it points to can! • const int * const r.

*r. *q. int n. and assign it to r – n may be negative CS-2303. C-Term 2010 Arrays in C & C++ 35 . q = p + 1. – Construct a pointer to a double that is n doubles beyond *p. – Construct a pointer to the next integer after *p and assign it to q • double *p.Pointer Arithmetic • int *p. r = p + n.

what would be added to q to get p CS-2303. – n is the number of floats between *p and *q. p++. i..e. n = p – q. decrement q to point to the previous long int • float *p. int n. *q. – Increment p to point to the next long int. *q.Pointer Arithmetic (continued) • long int *p. C-Term 2010 Arrays in C & C++ 36 . q--.

n = p – q.e. *q. p++. – n is the number of floats between *p and *q.Pointer Arithmetic (continued) • long int *p. what would be added to q to get p CS-2303. C-Term 2010 Arrays in C & C++ 37 . – Increment p to point to the next long int.. *q. q--. i. decrement q to point to the previous long int • float *p. int n.

Why introduce pointers in the middle of a lesson on arrays? • Arrays and pointers are closely related in C – In fact. – Type of A is int * – p = A. is the same as p = A + 5. they are essentially the same thing! – Esp. CS-2303. and A = p. C-Term 2010 Arrays in C & C++ 38 . when used as parameters of functions • int A[10]. are legal assignments – *p refers to A[0] *(p + n) refers to A[n] – p = &A[5]. int *p.

vs. – double *A sets aside one pointer-sized unit of memory. • Only difference:– – double A[10] sets aside ten units of memory. C-Term 2010 Arrays in C & C++ 39 . and A is initialized to point to the zeroth unit. not initialized • You are expected to come up with the memory elsewhere! – Note:– all pointer variables are the same size in any given machine architecture • Regardless of what types they point to CS-2303.Arrays and Pointers (continued) • double A[10]. each large enough to hold a double. double *A.

• assigns the pointer value B to the pointer value A • Original contents of array A are untouched (and possibly unreachable!) CS-2303. C-Term 2010 Arrays in C & C++ 40 . double B[10].Note • C does not assign arrays to each other • E. – double A[10].g. A = B.

C-Term 2010 Arrays in C & C++ 41 . caller copies the value of a pointer to float into the parameter A • Called function can reference through that pointer to reach thing pointed to CS-2303. int arraySize). int arraySize). void init(float *A.e.Arrays as Function Parameters • void init(float A[]. • Are identical function prototypes! • Pointer is passed by value • I.

n < arraySize. for(n = 0.Arrays as Function Parameters (continued) • void init(float A[]. int arraySize){ int n. n++) A[n] = (float)n. C-Term 2010 Arrays in C & C++ 42 . } //init • Assigns values to the array A in place – So that caller can see the changes! CS-2303.

C-Term 2010 Arrays in C & C++ 43 . &array[count])) !=EOF && rc!=0) … double getLargest(const double A[].Examples while ((rc = scanf("%lf". const int sizeA) { double d. return (d > A[0]) ? d : A[0]. } else return A[0]. } // getLargest CS-2303. if (sizeA > 0) { d = getLargest(&A[1]. sizeA-1).

C-Term 2010 Arrays in C & C++ 44 .Result • Even though all arguments are passed by value to functions … • … pointers allow functions to assign back to data of caller • Arrays are pointers passed by value CS-2303.

it is recommended to specify const if you don’t want function changing the value of any elements • Reason:– you don’t know whether your function would pass array to another before returning to you • Exception – many software packages don’t specify const in their own headers. so you can’t either! CS-2303. C-Term 2010 Arrays in C & C++ 45 .Safety Note • When passing arrays to functions.

C-Term 2010 Arrays in C & C++ 46 .Questions? CS-2303.