PART I
C h a p t e r 2 0 :
U n s a f e C o d e , P o i n t e r s , N u l l a b l e T y p e s , a n d M i s c e l l a n e o u s T o p i c s
591
PART IPART I
Sample output is shown here. Your output may differ, but the intervals will be the same.
int double
1243464 1243468
1243468 1243476
1243472 1243484
1243476 1243492
1243480 1243500
1243484 1243508
1243488 1243516
1243492 1243524
1243496 1243532
1243500 1243540
As the output shows, pointer arithmetic is performed relative to the referent type of the
pointer. Since an
int
is 4 bytes and a
double
is 8 bytes, the addresses change in increments
of these values.
Pointer Comparisons
Pointers can be compared using the relational operators, such as
= =
,
<
, and
>
. However, for
the outcome of a pointer comparison to be meaningful, usually the two pointers must have
some relationship to each other. For example, if
p1
and
p2
are pointers that point to two
separate and unrelated variables, then any comparison between
p1
and
p2
is generally
meaningless. However, if
p1
and
p2
point to variables that are related to each other, such
as elements of the same array, then
p1
and
p2
can be meaningfully compared.
Pointers and Arrays
In C#, pointers and arrays are related. For example, within a
fixed
statement, the name
of an array without any index generates a pointer to the start of the array. Consider the
following program:
/* An array name without an index yields a pointer to the
start of the array. */
using System;
class PtrArray {
unsafe static void Main() {
int[] nums = new int[10];
fixed(int* p = &nums[0], p2 = nums) {
if(p == p2)
Console.WriteLine("p and p2 point to same address.");
}
}
}
The output is shown here:
p and p2 point to same address.
www.freepdf-books.com
592
P a r t I :
T h e C # L a n g u a g e
As the output shows, the expression
&nums[0]
is the same as
nums
Since the second form is shorter, most programmers use it when a pointer to the start of an
array is needed.
Indexing a Pointer
When a pointer refers to an array, the pointer can be indexed as if it were an array. This
syntax provides an alternative to pointer arithmetic that can be more convenient in some
situations. Here is an example:
// Index a pointer as if it were an array.
using System;
class PtrIndexDemo {
unsafe static void Main() {
int[] nums = new int[10];
// Index a pointer.
Console.WriteLine("Index pointer like array.");
fixed (int* p = nums) {
for(int i=0; i < 10; i++)
p[i] = i; // index pointer like array
for(int i=0; i < 10; i++)
Console.WriteLine("p[{0}]: {1} ", i, p[i]);
}
// Use pointer arithmetic.
Console.WriteLine("\nUse pointer arithmetic.");
fixed (int* p = nums) {
for(int i=0; i < 10; i++)
*(p+i) = i; // use pointer arithmetic
for(int i=0; i < 10; i++)
Console.WriteLine("*(p+{0}): {1} ", i, *(p+i));
}
}
}
The output is shown here:
Index pointer like array.
p[0]: 0
p[1]: 1
p[2]: 2
p[3]: 3
www.freepdf-books.com
Do'stlaringiz bilan baham: |