Four. Arrays and pointers.
001 The difference between an array and a vector is that the length of the array is fixed. Once the array is created, dynamic modification of the length is not allowed. Pointers can be used like iterators to traverse and retrieve elements in an array.
Modern C + + programs should use vector and iterator types as much as possible, rather than using low-level arrays and pointers. Arrays and pointers are used internally within the class implementation only when the speed is stressed.
The flaw in the 002 array is that there is no size () operation, which means that the programmer cannot know the length of a given array.
If you need to change the length of the array, you must declare a larger array and copy the contents of the original array into the new array.
003 References cannot define an array. Not all elements are arrays of references.
004 non-const variables and const variables that do not know the value until run time cannot be used as the dimensions defined by the array. (These two points are not the same as the C99 standard, dynamic creation See item No. 021)
Const unsigned buf_size = 512; The const variable.
int staff_size = 217; Non-const variable.
Const unsigned SZ = get_size (); The const variable is determined at run time.
Char Buf1[buff_size]; Ok.
Char buf2[buff_size + 1]; OK, constant evaluates the expression.
Double salaries[staff_size]; Error, non-const variable do dimension.
int Test_rest[sz]; Error, the run-time only determines the const variable.
005 Default initialization.
An array of built-in types defined outside the function, and the elements are initialized with 0.
An array of built-in types defined within a function, with no initialization of elements.
If it is an array of class type, the default constructor initialization is called, regardless of where it is defined.
006 Display initialization.
int ia[3] = {0, 1, 3};
Char ca1[] = {' C ', ' + ', ' + '};
Char ca2[] = {' C ', ' + ', ' + ', '/0 '};
Char ca3[] = "C + +"; CA3 and Ca2 have the same dimensionality and initialization values, containing four elements.
Char ca4[3] = "C + +"//This results in a compilation error because "C + +" is a string of length 4.
String Str_arr[3] = {"Hi", "Heipi"}; Str_arr[2] is a string type element with a null value.
007 Unlike vectors, an array cannot be initialized with another array, nor can an array be assigned to another array.
Individual compiler extensions support array replication, but you should avoid such applications if you want to write programs that run on different compilers.
008 the type of array subscript is size_t.
04008.cpp
#include < iostream >
Using Std::cout;
Using Std::endl;
int main () ... {
const int MAX = 10;
int Ia[max] = ... {0,1,2,3,4,5,6,7,8,9};
for (size_t IX = 0; ix < MAX; ++ix)
cout << Ia[ix] << "";
cout << Endl;
return 0;
}
Compile and run results
Nan@linux-g4n6:~/documents> g++ o-o 04008.cpp
nan@linux-g4n6:~/documents>./O
0 1 2 3 4 5 6 7 8 9
Nan@linux-g4n6:~/documents>
Programmers have to be careful to prevent arrays from going out of bounds because the array does not have a function like size () in the vector to support the length of the query array.
In fact, this method can be considered to calculate the length of the array: size_t ia_size = sizeof (IA)/sizeof (*ia);
The 009 pointer is used to point to the object, specifically, the pointer holds the address of another object.
Unlike iterators: pointers are used to point to a single object, Access elements by dereferencing (*), and iterators can only be used to access elements within the container.
String S ("Hello Heipi");
String *sp = &s; The SP points to string S.
String S_arr[2] = {"Hello", "Heipi"};
SP = S_arr; The SP points to the first element of the string array, "Hello"
To understand Pointer declaration statements, read from right to left.
010 when the pointer is defined, it must be initialized (point to the specific object, either initialized to 0, or null,null defined in the Cstdlib header file).
There are four types of pointers that are initialized or assigned:
1.0-Value "constant" expression, note that using an int variable with a value of 0 to initialize a pointer is an error usage.
2. The address of the type match object.
3. Match the next address of the object.
4. Another valid pointer of the same type.
011 void* pointer, you can save the address of any type of object. He indicates that the pointer is related to an address, but does not know the type of object stored on this address.
A const void* pointer that can be used to hold the address of a const type object.
Double pi = 3.14;
Double *DP = π
void *VP = π
VP = DP;
The 012 pointer gets the object through the * operation, can be accessed, or can be modified.
cout << *DP;
*DP = 9999;
cout << *DP;
013 pointers and references: references always point to a fixed object, must be initialized when defined, and cannot be modified to point to another object.
The modification to a reference is to modify the value that it points to the object. Modify the pointer so that the pointer points to the new object.
Double &dp1 = pi;
Double obj1 = 2.34;
DP1 = obj1; At this point the Pi becomes 2.34, and the obj1 value is the same.
DP = OBJ1; At this point the DP no longer points to Pi, and PD points to obj1.
014 pointer to pointer.
Double **DPP = &dp;
cout << **DPP;
015 pointer to an array.
const int MAXSIZE = 5;
int Ia[maxsize] = {0, 2, 4, 6, 8};
int *IP = IA; When you use an array name in an expression, the name is automatically converted to a pointer to the first element of the array.
IP = &ia[3]//IP points to element 6.
016 the arithmetic operation of the pointer.
int *IP2 = IP + 1; Ip2 points to element 8.
ptrdiff_t dist = IP2-IP; The Ptrdiff is defined in the Cstddef header file.
cout << * (IP + 1); Equivalent to cout << *ip2, you need to pay attention to the application of parentheses.
017 C + + allows the pointer to point to an out-of-the-end address of an array or object, but does not allow the address to be dereferenced.
int *ip_head = IA;
int *ip_end = Ip_head + MAXSIZE; You can reference this address, but you cannot dereference the value (meaningless value).
for (int *tmp = Ip_head; tmp! = Ip_end; ++tmp) {//Here, the pointer is an iterator to the array.
cout << *tmp << Std::endl;
}
018 a pointer to a const object must also be of type Const, and the value of the object pointed to by the const pointer cannot be modified by dereference.
const int *IP3 = &MAXSIZE; IP3 points to maxsize, but the value of maxsize cannot be modified by *IP3.
int itmp = 9;
IP3 = &iTmp; Although Itmp is a non-const type, IP3 can point to itmp but still cannot be modified by *IP3.
It is also wrong to assign the address of a const object to a normal, non-const object pointer.
int *IP4 = &MAXSIZE; Error, IP4 is not a pointer to a const object.
Pointers to const objects are often used as formal parameters to prevent accidental modification of actual variables.
The 019 const pointer means that the pointer itself cannot be modified, and the const is behind the *.
int counter = 9;
int *const IP5 = &counter; IP5 is a pointer to counter.
*IP5 = 999; OK, you can modify its value by *IP5.
IP5 = IA; The error is that you cannot point IP5 to other types.
IP5 = IP5; Error, Hey, Ip5 Fu to himself also not, don't bother.
A const pointer to a const object.
const int *const IP6 = &MAXSIZE; IP6 points to maxsize, you can refer to the value of maxsize by *IP6, no other use.
Special attention is paid to the use of const and typedef in error prone areas.
typedef string *pstring; Pstring is a pointer to a string type.
Const Pstring CStr; CStr is a string *const variable, which is a const pointer to a string type.
Some people misunderstand that this is a const string type, remember? const is a description of CStr!
pstring Const CSTR1; OK, this statement is the same as the statement above CStr.
020 the type of string literal, which is an array of const char types. In C + +, this type should not continue to be used because it is the source of a large number of security issues.
const char *CP = "some value";
while (*CP) {
cout << *CP;
++CP;
}
The standard library of C-style strings, connection and copy operations must ensure that S1 has enough space, otherwise the consequences will be extremely dangerous.
#include <cstring>;
Strlen (s); Returns the length of S, not including the string terminator.
strcmp (S1,S2); The dictionary order compares the size of the S1 s2 two strings, returns 0 for the same, and a positive number represents S1 greater than S2.
strcat (S1,S2); Connect the S2 to S1 and return to the S1.
strcpy (S1,S2); Copy the S2 into the S1.
Strncat (S1,s2,n); Connect the first n characters of the S2 to the S1, and return to the S1.
strncpy (S1,s2,n); Copies the first n characters of the S2 to S1 and returns S1.
Never forget that the string terminator is null.
021 The memory space used to hold dynamically allocated objects is called free storage or "heap".
C is allocated with malloc and free, while C + + uses new and delete.
Defines a dynamic array.
int *ipa1 = new INT[10]; Because int is a built-in type, IPA is not initialized.
int *IPA2 = new INT[10] (); IPA2 are initialized to 0.
String *spa = new String[5]; The spa allocates 5 string spaces, and each string object is initialized to empty.
New can create a pointer of length 0, at which point the returned address is valid and can be compared, but cannot be dereferenced.
size_t num = get_size (); The pass get_size () function returns the length of the array.
int *ipa3 = new Int[num] (); Ok.
A dynamic array of const objects.
const INT *PI1 = new Const INT[10]; Error, this is not possible and must be initialized.
const INT *PI2 = new Const INT[10] (); OK, all initialized to 0.
Using delete [] frees the array space, and if empty square brackets are omitted, it causes the program to run in error. This results in less free memory space and a memory leak.
delete [] IPA1;
022 for string types, you can use the C_STR function to return an array of const char types.
const char *STR = S.C_STR ();
023 initializes the vector object with an array.
Const size_t arr_size = 6;
int Int_arr[arr_size] = {0, 1, 2, 3, 4, 5};
Vector<int> ivec1 (Int_arr, Int_arr + arr_size); The IVEC1 contains all Int_arr elements.
Vector<int> ivec2 (Int_arr + 1,int_ary + 3); The IVEC2 consists of three elements.
024 multi-dimensional arrays. In C + +, an array of arrays.
The results of the two initialization below are the same.
int Ia1[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}};
int ia2[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
A pointer to a multidimensional array.
int *ip[4]; An array of pointers to integers, ip[0],ip[1],ip[2],ip[3] are pointers to integers.
int (*IP) [4] = IA; IP is a pointer to an array pointer that contains four integer-type elements.
The bottom two defines a definition that is equal to the upper one.
typedef int INT_ARRAY[4];
Int_array *ip = ia;
for (Int_array *p = ia; p!= ia + 3; ++p)
for (int *q = *p; Q! = *p + 4; ++q)
cout << *q << Endl;
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.