linhungsam wrote: |
---|
1 2 3
|
int * i;
*i = 0;
for (i; *i < 1000000000; (*)i++)
|
(sic) |
I think you've misunderstood pointers. The first of your two code segments is the correct one.
Pointers need to point to an address of another variable or to the address of the first block (byte) of a region of memory. Pointers cannot point to numerical literals, except for zero (considered NULL). NULL is C++'s way of saying that the pointer isn't pointing to an actual address.
Here's an example that shows the incorrect use of a pointer:
1 2 3 4 5 6 7 8 9 10
|
int main( )
{
int *Pointer( nullptr );
// Place a numerical literal into the address pointed to
// by Pointer.
*Pointer = 100;
return 0;
}
|
Here, since
Pointer isn't pointing to a valid address (
nullptr is C++0x's new NULL), the write operation results in an access violation. Instead, pointers need something to point to in order to use them as intended. For example, consider this:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main( )
{
int Data( 0 );
int *Pointer( &Data );
// Place a numerical literal into the address pointed to
// by Pointer.
*Pointer = 100;
return 0;
}
|
Here,
Pointer is now pointing to the address of the first of 4 bytes of
Data. When we dereference
Pointer, the data within the address pointed to by
Pointer is read/written to. As I said before, pointers can also point to the first byte of an allocated block. For example:
1 2 3 4 5 6 7 8
|
int main( )
{
int *Pointer( new( std::nothrow ) int[3] );
delete [] Pointer;
return 0;
}
|
In this code segment, a block of 12 bytes is allocated during the construction of
Pointer. Now,
Pointer is pointing the the first byte of the first integer within the array.
Wazzak