ผลต่างระหว่างรุ่นของ "Adt lab/pointers"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
แถว 18: แถว 18:
 
   int a = 10;
 
   int a = 10;
 
   int b = 20;
 
   int b = 20;
 +
 
   p = &a;
 
   p = &a;
 
   cout << (*p) << endl;
 
   cout << (*p) << endl;
แถว 30: แถว 31:
 
   a = *p;
 
   a = *p;
 
   cout << a << endl;
 
   cout << a << endl;
 +
</source>
 +
 +
Let's look at each step.
 +
 +
<source lang="cpp">
 +
  p = &a;                  // step 1
 +
</source>
 +
 +
To obtain a location of any variable, we use operator <tt>&</tt> (called a ''reference'' operator).  After step 1, <tt>p</tt> keeps the location of <tt>a</tt>.
 +
 +
<source lang="cpp">
 +
  *p = 100;                // step 2
 +
</source>
 +
 +
To ''dereference'' a pointer variable, we use operator <tt>*</tt>.  Therefore <tt>*p</tt> refers to the "data" at the location that <tt>p</tt> points to.  After step 2, <tt>*p</tt> (which is essentially <tt>a</tt>) becomes 100.
 +
 +
<source lang="cpp">
 +
  a++;                      // step 3
 +
</source>
 +
 +
<source lang="cpp">
 +
  p = &b;                  // step 4
 +
  a = *p;
 
</source>
 
</source>
  

รุ่นแก้ไขเมื่อ 15:48, 27 สิงหาคม 2558

This is part of adt lab.

Pointers

In C/C++, there is a special kind of types: pointers. Pointer variables keep locations in the memory. To declare a pointer variable, we use symbol *:

type* variable;

For example, the following code declares p as a pointer to an integer.

  int* p;

To see how pointers work, let's follow this code.

  int a = 10;
  int b = 20;

  p = &a;
  cout << (*p) << endl;

  *p = 100;
  cout << a << endl;

  a++;
  cout << (*p) << endl;

  p = &b;
  a = *p;
  cout << a << endl;

Let's look at each step.

  p = &a;                   // step 1

To obtain a location of any variable, we use operator & (called a reference operator). After step 1, p keeps the location of a.

  *p = 100;                 // step 2

To dereference a pointer variable, we use operator *. Therefore *p refers to the "data" at the location that p points to. After step 2, *p (which is essentially a) becomes 100.

  a++;                      // step 3
  p = &b;                   // step 4
  a = *p;

Pointers and arrays

Other links