Skip to main contentCal State San Bernardino / [CNS] / [Comp Sci Dept] / [R J Botting] >> [CSci202] >> 03
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Contact] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Tue Apr 24 15:08:54 PDT 2007

Contents


    CSci202 Computer Science II, Session 03, How RAM works: data and pointers

      Previous

      [ 02.html ]

      Preparation

      Study this page and chapters 5 but not section 5.4.8 and write down the questions, doubts, and surprises that you have on a piece of paper. Include your printed name and a page number!

      Assigned Work Due

      Hand in your questions, doubts and surprises complete with the page number in the book and your name.

      Can submit project1 for a bonus.

      Quick Exercise

      Write a C++ program to read in 7 characters into an array and then print them out again. You can use the book if you wish. Style: the simplest thing that might possibly work.

      [ 03.cpp ]

      Exercise on RAM

      Either
      Case
        Draw a picture of the RAM in a Computer

      (End of Case)
      Case
        Write a paragraph describing the RAM in a Computer

      (Close Case )

      Topics in Chapter 5

      1. Integer types
      2. Floating types
      3. sizeof (demo [ sizeof.cpp ] )
      4. Pointers
      5. typedef [ typedef.html ]
      6. void -- a nontype!
      7. enum{red,amber,green}stoplight; -- see Enumerations below.
      8. Tables: vectors (and arrays).
      9. Pairs: useful <utility>

      Examples

      Simple pointers: [ 03b.cpp ]

      Input

        Basics

      1. You need to understand how programs work.... and this means understanding Primary Memory or RAM for short.
      2. Key prerequisite: Chapter 1, page 2, Figure 1.2. Your program is stored in Primary Memory (RAM) when it is running. Both the code, the data, and the variables must be in RAM before it can be used.
      3. Key fact: RAM is a long array of bytes. Each byte is 8 bits and can hold one char. They are numbered 0,1,2,3,4,... These numbers are called addresses. Each variable in a program is linked to a range of address and its value is stored in this location. The number of bytes depend on the type of variable and the compiler/operating system/CPU.
      4. Think of RAM as a table:
        Address0123456...33000...
        Location???????...?...

        Tracing

        How to trace a program.
        1. One column per variable
        2. One row per step.
        3. Record each change of value.

        The Stack

        AV Demos of how computer memory works as functions are called [ mem00.htm ]

        Pointers

        [ pointers.html ] [ 12frame.html ]

        Enumerations

        One of the simplest and safest ways to make you programs easier to read and so easier to debug and maintain is to give names to things.

        For example, you should not use "magic numbers" in code like this:

         		for(int i=0; i<7; i++) ...
        when you are really counting the days in the week. Instead define a constant
         		const int DaysInWeek = 7;
        and write
         		for(int i=0; i<DaysInWeek; i++) ...

        But an enumerated type makes your code even clearer:

         		enum Day{ sun,mon,tue,wed,thu,fri,sat};
        with code
         		for(Day day = sun; day <= sat; day++) ...

        By the way --- the C++ compiler replaces the ids in the enum by ints and so outputting them produces numbers! So I find I always need a helper array

         		string days[]={"Monday", "Tuesday", ...., "Sunday"};
        to handle output (and input).

        In class I compared code that had statements like this

         		light=0;
         		...
         		light=1;
         		...
         		light=2;
        with code with statements like
         		light=red;
         		...
         		light=yellow;
         		...
         		light=green;
        (now you know it is about stop lights);


        (exercise1): complete the following declaration

         		enum StopLight{ _____, ______, ______};
        (see answer1 below)

        The cost: a little bit of thinking and an extra line of code at the start of your program (between the #includes and the first function declaration). The result: you reduce confusion, increase clarity, and earn thank you points from the people who work on your code (including you) three years later. The risks: minimal. The catch: enumerated data is stored as integers (int) and so are input and output as a decimal number. But the good news: anything that works with int's also works with enum's -- arithmetic, parameters, return, for, while, if, ....

        Enumerated types often turn up as the states of objects. For example:

         		enum PersonState{ baby, child, preteen, teenage, adult, senior};
         		enum CoupleState{ date, married, divorced };
         		enum Hockey{ normal, powerplay};

        Open exercise: think about a program you'd like to write -- something useful (intensive care) or entertaining(a game)... Find an enumerated set of values for something.

        I used an enumerated type when I wrote my versions of Conway's life game. In this you have a square array (or table) of cells and each cell is either alive or dead:

         	enum cellstate{ dead, alive } ;
        and to handle input and out I also defined:
         	char outmap[]={'.', 'X'};
        Now I could declare the board as
         	cellstate b[LINES][COLS];
        (Notice -- no magic numbers. LINES and COLS are defined a consts elsewhere). I printed the board with code like this
         for(int r=0; r<LINES; r++)
         	{//print line
         	  for(int c=0; c<COLS; c++)
         		cout << outmap[b[r][c]];
         	  cout << "\n";
         	}//print line
        Now, the whole code can be found in [ http://www.csci.csusb.edu/dick/examples/ ] but, be warned, it uses concepts that we won't be covering for a couple of classes yet.

        Here is another example from [ ../examples/people.cc ]

         	enum Gender{UNKNOWN_GENDER=0, MALE = 1, FEMALE = 2};
        which is part of my family tree example (more later). Enumerated types are just plain useful... and simple... and safe.

      . . . . . . . . . ( end of section Input) <<Contents | End>>

      Questions

        One will be answered, at least, from each person. Some in class, some on paper, and some will be recorded here before the next class.

        Will we input numbers in Two's complement

        No. We will input and output data in decimal -- our computers all use (internally) two's complement and C/C++ translates it for us.

        (exception -- there may be an problem in the book that needs binary input/output).

        Waring: lots of binary conversions needed in hardware classes.

        What are pointers for

        They used in C and C++ to remember where data is stored.

        They are used to communicated addresses to functions in parameters so that the function's code can aces and change the outside data.

        They are used simply because a pointer takes up 4 bytes and can refer to an array or object with 10,000 bytes of data. It is much quicker to pass the 4 bytes than copy the 10Kb!

        Pointers to char are used to implement <string>.

        The address of an array is a pointer and so pointers are used to share arrays of data with functions.

        Pointers are used to remember where data is, when we create data on the heap -- because we didn't know until the program ran how much data to store.

        Pointers are used to link objects together -- one object knows where to find another object because it stores the address of the other object.

        C and C++ solve lots of technical problems by using pointers.

        What is the asterisk used for with a pointer.

        If p is a pointer then *p is the pointee -- the thing it points at.

        The asterisk is used in declaring pointers.

        Can you explain pointers?

        I can try but they are subtle.

        First all pointers are declared like this:

         		T * v ....;
        where v is a variable and T a type (or class name).

        An int is stored in a location and has an address. It has a value that is an int. A pointer to an int (int*) is stored in a location, and has an address. However, the address contains another address. This address contains an int.:

         		int i = 5;
         		int* cp = &i;//the address of i
         		//Now *cp is 5.

        When to use pointers

        1. When we don't know the size of some data until the program is running. Then we are forced to grab data off the head using the new operator and this returns the address of the storage we have been given.
        2. When we have a big amount of data in an array, vector, string, or other object and want to avoid copying it.
        3. When we need to reorganize data many times. Instead of putting it in a vector and moving it we include pointers to indicate what follows what. We reorganize by changing pointer values.
        4. When we want behavior that varies depending on the object being pointed at (see polymorphism later).

        How do references and pointers differ

        A pointer is declared like this
         		T *p...
        but a reference like this
         		T&r...
        Both name addresses but
        PropertyPointerReference
        declared byT*p...T&v...
        address isp-
        value is*pr
        points atchangesfixed
        ageoldnew .Raw safe? NO YES

        Difference between (*pv).push_back(1) and pv->push_back(1)

        None.

        Why should I care about sizeof

        1. Curiosity.
        2. Estimating the cost (RAM, Time) of your program.
        3. Two find out how much data needs to be copied, stored, input, or output using raw data.
          Given a void* that refers to an object you can use sizeof to compute how many bytes to access, copy, store, or return.
          To computer the size of array a use
           		sizeof(a)/sizeof(a[0])

        Explain void and void*

        The word void got into C to indicate that a function did not return a value:
         		void name(...)...
        or to state that it must not have arguments/parameters:
         		....name(void)...

        Then people used void* to mean: a pointer at an object of unknown type.

        Have pointers changed from C to C++?

        No. We just don't need them as much.

        Why does the code for strcpy on page 169 do anything?

         		while( *(p++) = *(q++) );
        You might guess that this is a test for equality. But beware such naive mistakes. The equals sign in C/C++/Java is a command to copy the data even inside a condition like
         		while( .... )
        The
         		*(p1) = *(q1)
        copies an item from one place to another.

        Next trick the pointers are move on to the next place (p++) and (q++) after the assignment.

        So what is tested? When an assignment finishes it leaves a copy of the value behind that can be tested! In this case the character moved. When a null character ('\0') is moved the loops stops.

        Next trick the pointers are move on to the next place (p++) and (q++) after the assignment.

        So what is tested? When an assignment finishes it leaves a copy of the value behind that can be tested! In this case the character moved. When a null character ('\0') is moved the loops stops.

        Is the basic use of typedef to simplify complex declarations

        This is one use. Another use is to make a program easier to understand by using a meaningful name for some concept that the data type encodes.

        What are pairs

        These are a useful and simple tool in the <utility> library. Each pair p has two parts: p.first and p.second. They can be of any type. The can be of the same or a different types. There is a special function that constructs a pair for us.

        They are used in special containers to connect a key (a name say) with some data (the person's phone number).


    . . . . . . . . . ( end of section Questions) <<Contents | End>>

    Quiz

    See Next below!

    Lab

    Arrays are insecure unless you are are very careful: [ lab02.html ]

    Next

    Project 1
  1. project1::= See http://csci.csusb.edu/dick/cs202/project1.html is due at start of the next class.

    Study Chapter 6 on Objects [ 04.html ]

    There will be a Quiz on first 5 chapters and/or your project. Structure: 1 question asking you to fill in blanks in code based on topics in chapters 1,2,3, and/or 4. Next tracing code based on topics in chapter 5. Third: questions on the code in you project.

    Answers


    (answer1):
     		enum StopLight{ red, yellow, green};
    (back to exercise1).

. . . . . . . . . ( end of section CSci202 Computer Science II, Session 03, How RAM works: data and pointers) <<Contents | End>>

Abreviations

  • TBA::="To Be Announced", something I have to do.
  • TBD::="To Be Done", something you have to do.
  • Dia::="A free Open Source Diagramming tool for Linux, Windoze, etc. ".

    End