5, the pointer

1, create a pointer

[1] exists in a C ++ pointer is created, the computer memory allocated for storing the address, rather than the pointer points allocated to store data.

[2] * before use to access variables, a pointer initialized to determine the proper address.

[3] To use the digital value as an address to be cast by a number into a pointer type.

int * Pt; 
Pt = 0xB8000000 ; // Error 
Pt = ( int *) 0xB8000000 ; // Valid

2, to allocate memory using new

As in C, with a malloc memory, C ++ may be used which also new.

to find the correct length of a new block of memory and returns the address of the memory block, the programmer will need to assign the address to a pointer.

int *pn=new int;

tells the program new int, int memory required for storage, new new operator to determine how many bytes of memory required according to the type, to find such a memory and returns the address.

pn points to a block of memory without a name, what to call it, we said pn points to a data object (here referred to as memory blocks instead of variables).

3, using the delete releases memory

int * ps = new new  int ;
 Delete ps;
 / * above statement frees the memory pointed ps, but does not delete the pointer itself ps, 
ps point to another may be newly allocated memory block * / 

int * PS2 = new new int;
int * pt = ps; // Do not create a general point to the same memory block pointer
// will increase the risk of mistakenly deleted the same memory block
return 0;

4, use new to create a dynamic array

/ * To allocate memory array is called static binding (static binding, means that the array is added to the program at compile time. At compile time 
when using the new, if you need an array is created in the operational phase, you can also choose the length of the array at run time, called dynamic binding. 
array created at runtime is called dynamic array. 
* / 
int * = psome new new int [10]; return address of the first element // new elements, and assigns psome
Delete [] psome; / / square brackets tell the program, you should release the entire array instead of a pointer to an element
  • You can not use delete release the allocated memory is not new
  • You can not use delete to release the same memory block twice
  • The use of new [] array to allocate memory, you should use delete []
  • The use of new [] as an entity to allocate memory, you should use delete
  • Null pointer using delete is safe
short tell[10];
cout << tell << endl;
cout << &tell << endl;

From said figures, the same tell & tell; Conceptually, however, tell refers & tell [0] is the address of a 2-byte block of memory, an address & tell the 20-byte memory block. tell + 1 will increment the address 2, & tell + 1 memory address plus 20.

tell a short pointer (* short), and to the containing short & tell array of 20 elements (short (*) [20]).

 

Guess you like

Origin www.cnblogs.com/gaoyixue/p/11460853.html
Recommended