Question

In: Computer Science

Pointers is a difficult concept for many students.  I'm not sure how to make students understand the...

Pointers is a difficult concept for many students.  I'm not sure how to make students understand the concept better. In an attempt to have you try to understand pointers, I'm going to ask you to write a paper that summarizes the chapter (or an online resource) that may help you understand the concept of pointers. Include the following topics in the paper. Include illustrations either from the book, or an online source or your own illustration.

  • Come up with an introduction
  • Pointer Variable Declarations and Initialization
  • Pointer Operators
  • Pass-by-Reference with Pointers
  • Built-In Arrays
  • Using const with Pointers
  • sizeof Operator
  • Pointer Expressions and Pointer Arithmetic
  • Relationship Between Pointers and Built-In Arrays
  • Pointer-Based String
  • About Smart Pointers

You may include additional topics and illustrations to maybe help someone else understand the concept. Upload your final paper to this assignment page.

Solutions

Expert Solution

Pointers:

  • A pointer is a variable whose value is the address of another variable.
  • It can be used to perform pass-by-reference.
  • It can be used to create and manipulate dynamic data structures

Pointer Variable Declarations and Initialization:

Pointer variables

  • Contain memory addresses as values.
  • Normally, variable contains specific value (direct reference)
  • Pointers contain address of variable that has specific value (indirect reference)

Pointer declarations

  • * indicates variable is a pointer
  • Example : int *myPtr;
  • Declares pointer to int, of type int *
  • • Multiple pointers require multiple asterisks int *myPtr1, *myPtr2;

Pointer initialization:

  • Initialized to 0, NULL, or an address.
  • 0 or NULL points to nothing (null pointer).

Pointer Operator:

  • Address operator (&)
  • Returns memory address of its operand
  • Example
    • int y = 5;
    • int *yPtr;
    • yPtr = &y;
    • assigns the address of variable y to pointer
      • variable yPtr – Variable yPtr “points to” y
      • yPtr indirectly references variable y’s value
  • * operator
  • Also called indirection operator or dereferencing operator
  • Returns synonym for the object its operand points to
  • *yPtr returns y (because yPtr points to y)
  • Dereferenced pointer is an lvalue
    • *yptr = 9;
  • * and & are inverses of each other
    • Will “cancel one another out” when applied consecutively in either order

Pass-by-Reference with Pointers:

  • Simulates pass-by-reference
    • Use pointers and indirection operator
  • Pass address of argument using & operator
  • Arrays not passed with & because array name is already a pointer
  • * operator used as alias/nickname for variable inside of function

Using const with Pointers:

  • const qualifier
    • Indicates that value of variable should not be modified
    • const used when function does not need to change the variable’s value

sizeof Operator:

  • Returns size of operand in bytes
  • For arrays, sizeof returns
    • ( size of 1 element )
    • * ( number of elements )
  • If sizeof( int ) returns 4 then
    • int myArray[ 10 ];
    • cout << sizeof( myArray );
    • will print 40
  • Can be used with
    • Variable names
    • Type names
    • Constant values

Pointer Expressions and Pointer Arithmetic:

  • Pointer arithmetic
    • Increment/decrement pointer (++ or --)
    • Add/subtract an integer to/from a pointer (+ or +=, - or -=)
    • Pointers may be subtracted from each other
    • Pointer arithmetic is meaningless unless performed on a pointer to an array
  • 5 element int array on a machine using 4 byte ints
    • vPtr points to first element v[ 0 ], at location 3000 vPtr = &v[ 0 ];
    • vPtr += 2; sets vPtr to 3008 (3000 + 2 * 4)
      • vPtr points to v[ 2 ]
  • Subtracting pointers
    • Returns number of elements between two addresses vPtr2 = v[ 2 ];
    • vPtr = v[ 0 ];
    • vPtr2 - vPtr is 2
  • Pointer assignment
    • Pointer can be assigned to another pointer if both are of same type
      • If not same type, cast operator must be used
      • Exception
        • Pointer to void (type void *)
          • Generic pointer, represents any type
          • No casting needed to convert pointer to void *
          • Casting is needed to convert void * to any other type
          • void pointers cannot be dereferenced
  • Pointer comparison
    • Use equality and relational operators
    • Compare addresses stored in pointers
      • Comparisons are meaningless unless pointers point to members of the same array
    • Example
      • Could show that one pointer points to higher-index element of array than another pointer
    • Commonly used to determine whether pointer is 0 (null pointer)

Relationship Between Pointers and Built-In Arrays:

  • Arrays and pointers are closely related
    • Array name is like constant pointer
    • Pointers can do array subscripting operations
  • Accessing array elements with pointers
    • Assume declarations:
    • int b[ 5 ];
    • int *bPtr;
    • bPtr = b;
  • Element b[ n ] can be accessed by *( bPtr + n )
    • Called pointer/offset notation
  • Addresses
    • &b[ 3 ] is same as bPtr + 3
  • Array name can be treated as pointer
    • b[ 3 ] is same as *( b + 3 )
  • Pointers can be subscripted (pointer/subscript notation)
    • bPtr[ 3 ] is same as b[ 3 ]

Pointer-Based String:

  • String
    • Series of characters treated as single unit
    • Can include letters, digits, special characters +, -, *, ...
    • String literal (string constants)
      • Enclosed in double quotes, for example:
        • "I like C++“
      • Have static storage class
    • Array of characters, ends with null character '\0'
    • String is constant pointer
      • Pointer to string’s first character
        • Like arrays
    • String assignment
      • Character array
        • • char color[] = "blue";
        • Creates 5 element char array color
          • Last element is '\0'
    • Variable of type char *
      • char *colorPtr = "blue";
        • Creates pointer colorPtr to letter b in string "blue"
          • "blue" somewhere in memory
    • Alternative for character array
      • char color[] = { 'b', 'l', 'u', 'e', '\0' };
  • Reading strings
    • Assign input to character array word[ 20 ]
      • cin >> word;
        • Reads characters until whitespace or EOF
    • String could exceed array size
      • cin >> setw( 20 ) >> word;
        • Reads only up to 19 characters (space reserved for '\0')
  • cin.getline
    • Read line of text
      • cin.getline( array, size, delimiter );
        • Copies input into specified array until either
          • One less than size is reached
          • delimiter character is input
    • Example
      • char sentence[ 80 ];
      • cin.getline( sentence, 80, '\n' );

Smart Pointers:

  • Smart pointers are used to make sure that an object is deleted if it is no longer used.
  • void abc()
    {
        int* tr = new int(10);
        int x = 45;
        // .....
        if (x == 45)
            return;   // here we have a memory leak, valuePtr is not deleted
        // ...
        delete ptr;
    }
     
    int main()
    {
    }

Related Solutions

I'm currently looking at this figure, but I'm not sure how to interpret it. If I'm...
I'm currently looking at this figure, but I'm not sure how to interpret it. If I'm not mistaken, the energy loss of the muon (This is a muon that penetrates copper) is on the y-axis. But does that just mean, that if my muon has energy of around 0.5 GeV, then it has a stopping power around 2 MeV cm2/g (Minimum ionization), which means it loses that amount of energy pr. cm2/g? To me that just seems a bit "linear"....
Trying to make sure I'm answering these questions correctly. I'm confused on question d. I can...
Trying to make sure I'm answering these questions correctly. I'm confused on question d. I can explain why in terms of concentration gradient and the fact it's in a hypotonice solution which would cause water to go into the blood vessel, but don't know how to answer it in terms of hydrostatic pressure. 6. Imagine blood in a vessel that has an osmolarity of 300 mEq (a measure of the concentration of particles). Now, imagine that the IF around the...
I'm new to finance and I'm not sure how to use the summary charts that well,...
I'm new to finance and I'm not sure how to use the summary charts that well, so I was wondering if I could find a stock summary for the last three weeks of May. I just need the close of market, stock price, beta, eps, p/e, dividend and market capitalization for VNO and SPG. If it is possible i'd like to know where and how to find it. Thanks in advance.
Why is it difficult for many to know and understand when to either reject the null...
Why is it difficult for many to know and understand when to either reject the null hypothesis or revise the hypothesis and repeat the process?
I'm not sure i understand sending parameters and reference and i think im doing it wrong....
I'm not sure i understand sending parameters and reference and i think im doing it wrong. In this code i'm trying to enter notas (grades) by user input into the exArrays, getting the promedio (average) and printing it on screen. I've searched a lot of videos but they don't help. The lenguage is C++ void entrarNotas(int ex1Array[], int ex2Array[], int ex3Array[], int sizeSalon, char notaPara, float promedioPara) {    cout << "Entrar cuantos estudiantes hay en el salon" << "...
Hi! Below is the case study and I want to make sure I'm on the right...
Hi! Below is the case study and I want to make sure I'm on the right track. I bolded the questions I'm interested in (1-5). Looking for people who are familiar with the DSM-5/abnormal psychology and able to answer all questions completely. Thank you! Detailed answers extremely appreciated! Questions: 1. Diagnosis; what is the evidence for it? 2. Treatment; typical treatment used for this diagnosis AND most effective treatment. IF the person is in treatment, what should we target first...
Hi! Below is the case study and I want to make sure I'm on the right...
Hi! Below is the case study and I want to make sure I'm on the right track. I bolded the questions I'm interested in (1-5). Looking for people who are familiar with the DSM-5/abnormal psychology and able to answer all questions completely. Thank you! - no ICD 10 please! Questions: 1. Diagnosis; what is the evidence for it? For this one, assume the patient has borderline disorder and answer the rest accordingly. 2. Treatment; typical treatment used for this diagnosis...
Hi! Below is the case study and I want to make sure I'm on the right...
Hi! Below is the case study and I want to make sure I'm on the right track. I bolded the questions I'm interested in (1-5). Looking for people who are familiar with the DSM-5/abnormal psychology and able to answer all questions completely. Thank you! Questions: 1. Diagnosis; what is the evidence for it? 2. Treatment; typical treatment used for this diagnosis AND most effective treatment. IF the person is in treatment, what should we target first in terms of symptoms?...
Hi! Below is the case study and I want to make sure I'm on the right...
Hi! Below is the case study and I want to make sure I'm on the right track. I bolded the questions I'm interested in (1-5). Looking for people who are familiar with the DSM-5/abnormal psychology and able to answer all questions completely. Thank you! Detailed answers extremely appreciated! Questions: 1. Diagnosis; what is the evidence for it? 2. Treatment; typical treatment used for this diagnosis AND most effective treatment. IF the person is in treatment, what should we target first...
I'm being ask to design an experiment about enzymes. I'm not sure about how to do...
I'm being ask to design an experiment about enzymes. I'm not sure about how to do that. To test for the presence of monosaccharides and reducing disaccharide sugars in food, the food sample is dissolved in water, and a small amount of Benedict's reagent is added. The solution should progress in the colors of blue (with no glucose present), green, yellow, orange, red, and then brick red when there is a large amount of glucose present. Design an experiment where...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT