// a pointer may be assigned to "point to" the value of
// another variable using the & (address of) operator
//
// &
p = & j;
// since j was on the stack, this address will be somewhere
// on the stack. Pointers are printed in hex format using
// %p and conventionally marked with 0x.
//
j ,
// - .
// %p printf_s 0x.
printf_s("0x%p\n", p);
// The * (indirection operator) can be read as "the value
// pointed to by".
// Since p is pointing to j, this should print "2"
//
* ( ) "
"
// p j, "2"
printf_s("0x%p %d\n", p, *p);
// changing j will change the result of the indirection
// operator on p.
//
j
// p.
j = 7;
printf_s("0x%p %d\n", p, *p );
// The value of j can also be changed through the pointer
// by making an assignment to the dereferenced pointer
//
j
//
*p = 10;
printf_s("j is %d\n", j); // j
10
// allocate memory on the heap for an integer,
// initialize to 5
//
(heap) ,
// 5
p = new int(5);
// print the pointer and the object pointed to
// the address will be somewhere on the heap
//
// - (heap)
printf_s("0x%p %d\n", p, *p);
// free the memory pointed to by p
//
p
delete p;
// At this point, dereferencing p with *p would trigger
// a runtime access violation.
//
p *p
//
//
Pointer arithmetic may be done with an array declared
// on the stack or allocated on the heap with new.
// The increment operator takes into account the size
// of the objects pointed to.
//
// new.
//
//
p = new int[5];
for (i = 0; i < 5; i++, p++) {
*p = i * 10;
printf_s("0x%p %d\n", p, *p);
}
// A common expression seen is dereferencing in combination
// with increment or decrement operators, as shown here.
// The indirection operator * takes precedence over the
// increment operator ++.
// These are particularly useful in manipulating char arrays.
//
// ,
.
// * ++
//
char s1[4] = "cat";
char s2[4] = "dog";
char* p1 = s1;
char* p2 = s2;
// the following is a string copy operation
//
-
while (*p1++ = *p2++);