- Forward


Arrays in C++
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Definitions
Back SMYC Forward
  • Array:
    • A set of consecutive/contiguous memory locations used to store homogeneous data
  • Element:
    • An item in an array
    • (You refer to a particular element using its index)
  • Dimension:
    • The number of elements in an array
    • (An array of size/dimension n has indexes ranging from 0 to n-1 because the index is actually an offset from the first element)
Basics
Back SMYC Forward
  • A Typical Array Declaration:
    • int scores[10];
  • A Typical Use of an Array:
    • x = scores[3];
Strings as Arrays in C
Back SMYC Forward
  • The Issue:
    • C does not have a string data type
    • Instead, one uses an array of characters
  • An Observation:
    • There is no easy way to know the dimension of an array
  • An Implication:
    • All strings are terminated with the NUL character (i.e., '\0')
Strings as Arrays in C (cont.)
Back SMYC Forward

An Example

cppexamples/basics/strings.c (Fragment: 0)
 
Strings as Arrays in C (cont.)
Back SMYC Forward

Assignment to an Array?

char course[6]; course = "CS240\0"; // Invalid
Strings as Arrays in C(cont.)
Back SMYC Forward

Using string.h

cppexamples/basics/strings.c (Fragment: 1)
 
Strings as Arrays in C
Back SMYC Forward
  • Potential Buffer Overflows:
    • strcpy() can't know the size of the array so just copys whatever you tell it to, even if there isn't enough memory
  • Better Functions (that Still Require Care):
    • strncpy() which doesn't null-terminate if there isn't space
    • strncat() which does
Multidimensional Arrays
Back SMYC Forward
  • Arrays of Arrays:
    • Are allowed
  • A Typical Declaration:
    • int scores[30][5];
  • A Typical Use:
    • scores[0][3] = 100;
Arrays of C Strings
Back SMYC Forward

An Example

cppexamples/basics/strings.c (Fragment: 2)
 
Arrays of C Strings (cont.)
Back SMYC Forward
  • What happens if the second call to strcpy() in the above example is strcpy(courses[1], "GISAT200");?
  • Why?
An Aside: Strings in C++
Back SMYC Forward
  • The Idea:
    • Use a class to encapsulate a string
  • The Advantages:
    • Size can be known so no need for null-termination
    • Size needn't be fixed
An Aside: Strings in C++
Back SMYC Forward

An Example

cppexamples/basics/strings.cpp
 
There's Always More to Learn
Back -