|
|
|
Pointer Examples
1. Basic concepts
%
cat ptr1.cpp
//
pointer example 1
#include<iostream>
using
namespace std;
int
main()
{
// declare a variable
int temp = 5;
// declare a pointer
int *temp_ptr;
// assign the address of temp to the pointer
// using the address operator &
temp_ptr = &temp;
// display temp and temp_ptr
cout << "Value of temp
= " << temp << endl;
cout << "Address of temp = "
<< temp_ptr << endl;
// display the value of temp using temp_ptr
// and the dereferencing operator *
cout << "Value of temp:
*temp_ptr = " << *temp_ptr
<< endl;
return 0;
}
%
g++ ptr1.cpp
%
a.out
Value
of temp = 5
Address
of temp = 0x7fbffff89c
Value
of temp: *temp_ptr = 5
2. Pointers and arrays
%
cat ptr2.cpp
//
pointer example 2
#include<iostream>
using
namespace std;
int
main()
{
int data[5] = {12, 45, 19, 22, 37};
cout << "Pointers and
Arrays\n\n";
// the name of the array is a pointer to
the
// beginning of the array
//
//
(data + i) means the address of the beginning
// of the array plus i * the number of
bytes
to store
// an int (for this example)
//
// *(data + i) and data[i] are equivalent
cout << "i data[i]
*(data + i) (data + i)\n\n";
for(int i=0; i < 5; i++)
{
cout << i << " " << data[i] << " "
<<
*(data + i ) <<
" " <<
(data + i)
<< endl;
}
return 0;
}
% g++ ptr2.cpp
%
a.out
Pointers
and Arrays
i data[i]
*(data + i) (data + i)
0 12
12 0x7fbfffeb00
1 45
45 0x7fbfffeb04
2 19
19 0x7fbfffeb08
3 22
22 0x7fbfffeb0c
4
37
37 0x7fbfffeb10
|
|