JMU
Arrays in C++
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Definitions
Basics
Strings as Arrays in C
Strings as Arrays in C (cont.)

An Example

cppexamples/basics/strings.c (Fragment: 0)
            char course[6];

    course[0] = 'C';
    course[1] = 'S';
    course[2] = '2';
    course[3] = '4';
    course[4] = '0';
    course[5] = '\0';
        
Strings as Arrays in C (cont.)

Assignment to an Array?

  char course[6];

  course = "CS240\0"; // Invalid
  
Strings as Arrays in C(cont.)

Using string.h

cppexamples/basics/strings.c (Fragment: 1)
            char course[6];

    strcpy(course, "CS240"); // strcpy() will add the \0
        
Strings as Arrays in C
Multidimensional Arrays
Arrays of C Strings

An Example

cppexamples/basics/strings.c (Fragment: 2)
            char        courses[3][6];
    
    strcpy(courses[0], "CS149");
    strcpy(courses[1], "CS159");
    strcpy(courses[2], "CS240");
        
Arrays of C Strings (cont.)
An Aside: Strings in C++
An Aside: Strings in C++

An Example

cppexamples/basics/strings.cpp
        #include <string>
using namespace std;

int main(void) {

  string course = "CS240";
  int n = course.length();

  string courses[3];
  courses[0] = "CS149";
  courses[1] = "GISAT200";
  courses[2] = "CS240";
}