Array: Integer arrays: strings arrays:
Get:
1) The C in the middle number begins starting with 0, in order to access the last element in the array, we want to index array length
-1 position; 2) C does not support operation of the entire array, for example, different arguments assign an array to another array, or you can't know
The size of the digital group is equal to the two arrays; 3) Static memory allocation: The compiler is allocated at the time of handling the program source code; the efficiency is high, the flexibility dynamic memory allocation: the program is executed, the runtime library function is sent to allocate ;
Difference: Efficiency and flexibility balance;
For handling and storage of any text file, static allocation cannot be satisfied; that is, when the problem is not
When you know the size, you cannot complete the static allocation, because static allocation is dead before the program is executed.
And once the size cannot be determined, it cannot be specified.
4) Pointer int IVAL = 1024; // This format is associated with IVAL has two, one is 1024; one is
IVAL address INT * PINT; // a pointer to the int type (other type of pointer is defined ??) Pint = & = = * Put the address of IVAL to Pint * Pint = * Pint 1; / / Equal to IVAL = IVAL 1;
Pint is equivalent to an address, * PINT is the value in the retrieval address; IVAL is the value in the address, & IVal is the address corresponding to the value; (equivalent to: Dongfang Road, Lao Wang, then the old king is IVAL, PINT That is, No. 100, Orient, for the old king
Using & Operation, you can know that the address is 100 Dongfang Road. You can know the old king in Dongfang Road 100.
5) Two main differences between static & dynamic memory allocation: First, static objects are named, you can do it directly, for example, we know No. 100 Dongfang Road.
I live in the old king inside, we can do it directly;
Road 100 is a hotel, I don't know who I will live in; II. Static distribution program don't need to be done, and dynamic must be completed by new and delete expressions.
It is easy to errors;
For dynamic allocation, the only access method is to operate by means of an address;
6) New and Delete: New version: int * pint = new int (1024); // Assign an int class with no name
Type object, the initial value of the object is 1024, then the expression returns the address of the object in memory. Then, this address is used
To initialize the object PINT. (?? This address is determined, randomly or compile, presented
Should be PINT, if so, if you assign less memory to PINT? If pre-allocated, then how do you know the type of PINT?
? (Equivalent to the No. 100, Oriental Road, is giving the old king, but the program does not know who is the old king, I only know that it is personal, I am now living in Donggong Road, New is equivalent to the directive to the old king.)
INT * PIA = New int [1024]; // Assign an array containing 1024 integer elements, but we did not
The method knows the explicit initial value of this 1024 elements (equivalent to us to live in the No. 100, Oriental Road, but the course
In the order, he only knows to live 1024 people, who don't know anyone)
Two versions of DELETER and corresponding; delete pint; // Delete a single object
Delete [] PIA; / / Delete an array of objects (?? [] Why is in front)
7) Forgot the consequences of Delete, produce memory leaks, which can only be used once, actually
Static allocation (here is ignored a very important issue, if you execute multiple times, then the memory is constantly consumed
, Eventually leading to the system error, not simple equivalent to static allocation, it seems that my sensitivity is not enough, no wonder I don't
Is a hacker, ~~~~~~~~~~)
doubt:
1) Index and Index have different differences; 2) Why does C does not take arrays as a first-class citizen? What is it? Is it just because of inheritance from C? 3) All examples are used in int, what is the same time when other types? ? ?
For example, how to use new and delete to handle char,
Char * pia = new char [6]; // This should not be wrong, the INT format is used; but if I want
What should I do if I assign him to "Hello"? ? ?
Char * pia = new char ("hello"); // does not seem to, there is prawn to see the pointing, worship! ! Char * PIA = "Hello"; // This should have no problem, but where should NEW be added?
*********************************************************** ************************* Exercise 2.3 Say the difference between the four objects defined below (a) int = 1024; // Give IVAL a memory space, and initializes 1024 (c) int * pi2 = new int (1024); // assigns the memory space specified by the pointer * pi2 to 1024 (b) int * pi = & = & = & = The specified memory space is assigned the address (d) INT * PI3 = New INT [1024]; / / stores a memory space specified by the pointer * PI3 to 1024 yuan
Array of vegetarian
Exercise 2.4 The following code segment is what is doing what seriously wrong Note The usage of the subscript of the pointer PIA is the correct way to explain its reason INT * PI = New int (10); int * PIA = New int [10]; while (* pi <10) {PIA [* pi] = * pi; // cannot explicitly assign an array in dynamic pointer allocation * pi = * pi 1;} Delete Pi DELETE [] PIA; ************************************************************** ***********************************************************************************************
(1) Allocation from a static storage area. When the program is compiled, it has been allocated, and there is a program in this block.
There are existence during the entire run. For example, global variables, static variables.
(2) Created on the stack. When performing a function, the storage unit of local variables within the function can be created on the stack.
These storage units are automatically released at the end of the execution. The stack memory allocation operation is within the command set of the processor.
The rate is high, but the distributed memory capacity is limited.
(3) Distribution from the pile, also known as dynamic memory allocation. How much is the program to apply for a malloc or new when running?
Memory, programmers you are responsible for the release of memory with free or delete. Dynamic memory survival is determined by us
It is very flexible to use, but the problem is most.
*********************************************************** ************************************************************************************************** The compiler cannot automatically discover these errors, usually in the program
Can capture it. Most of these errors do not have obvious symptoms, and sometimes the difficulty of inclination is increased. Have
When the user is angry, I find you, but the program has not happened any problems. You walk, the mistake is also episodes.
Common memory errors and their countermeasures are as follows:
1) The memory allocation is unsuccessful, but it uses it.
Programming newcomers often make this mistake because they don't realize that memory allocation will be unsuccessful. Commonly used solution is,
Check if the pointer is NULL before using the memory. If the pointer P is the parameter of the function, then in the entrance to the function
Assert (p! = null) check. If you apply for memory with Malloc or New, you should use if (p == null) or
IF (p! = null) performs prevention error.
2) Although memory allocation is successful, it is not initialized to reference it.
There are two main causes of this mistake: First, there is no concept of initialization; the second is that the default initial value of memory is all
Zero, leads to a reference initial value error (such as an array).
The default initial value of memory does not have a unified standard, although some time is zero, we would rather believe
Not credible. So don't forget to assign initial values, even if you are zero value.
Slightly, don't be troublesome.
3) The memory allocation is successful and has been initialized, but the operation crosses the boundary of the memory.
For example, when using an array, the subscript "more 1" or "less 1" is often generated. Especially in the For cycle statement,
The number of cycles is easy to make mistakes, causing array to operate the offshore.
4) Forgot to release memory, resulting in memory.
A function containing such an error is lost once a time is called once. At the beginning, the system's memory is sufficient, you can't see it.
Go to the error. I have finally dead, and the system prompts: memory consumption.
Dynamic memory application and release must be paired, the number of malloc and free usage will be the same, otherwise there must be an error (New / Delete.).
5) Release the memory but continue to use it.
Three cases:
(1) Object call relationship in the program is too complicated, and it is really difficult to figure out whether an object has been released.
Save, the data structure should be redesigned, fundamentally resolve the chaotic situation of the object management.
(2) The RETURN statement of the function is wrong, be careful not to return "pointer" or "reference" to "stack memory"
Since the memory is automatically destroyed at the end of the function body.
(3) After using Free or Delete releases the memory, the pointer is not set to NULL. Resulting in a "wild pointer".
*********************************************************** ***************** [Rule 7-2-1] After using Malloc or New to apply for memory, you should immediately check if the pointer value is NULL. . Prevention
Use the pointer value to NULL memory.
[Rule 7-2-2] Don't forget to be a first value for array and dynamic. Prevent memory that will not be initialized as right values
use.
[Rule 7-2-3] Avoid the subsidiaries of array or pointer, especially "more than 1" or "less 1" operation occurs.
[Rule 7-2-4] The application and release of dynamic memory must be paired to prevent memory leakage.
[Rule 7-2-5] After using Free or Delete released the memory, set the pointer to NULL to prevent "wild"
pointer".
*********************************************************** ***********************************
The difference between arrays and pointers
In C / C procedures, pointers and arrays can replace each other in many places, which makes people an illusion that two
It is equivalent.
Arch is either created in a static memory area (such as global array) or created on the stack. The number of group names corresponds (
Instead of pointing) a piece of memory, its address and capacity remain unchanged within the lifetime, only the content of the array can be changed
.
The pointer can point at any type of memory block at any time, and its feature is "variable", so we often use pointers to operate
Performance memory. The pointer is far more flexible than the array, but it is also more dangerous.
One of the differences: arrays can be modified separately, and the pointer cannot be modified separately.
Char a [] = "Hello"; // a [] content is Hello / 0A [0] = 'x'; // can be modified separately for A [0]
Char * PIA = "world"; // PIA points to constant string PIA [0] = 'x'; // is wrong, can not assign one of the elements of it separately
Difference 2: Direct assignment and comparison
You cannot directly copy and compare the array names. In the example, if you want to copy the contents of the array A to an array B, it cannot be used
Statement b = a, otherwise compiling errors will be generated. You should use the standard library function STRCPY to be copied. Similarly, compare B
Whether the contents of A is the same, cannot be judged with if (b == a), and should be compared with the standard library function STRCMP.
The statement P = A does not copy the contents of the A, but assigns the address of A to P. To copy A content,
Can first use the library function malloc to apply a capacity of Strlen (a) 1 characters, and use strcpy
String replication. Similarly, statement if (p == a) is not content but addresses, should be compared with library functions strCMP.
// array
Char a [] = "Hello"; Char B [10]; STRCPY (B, A); // A assignment to B, pay attention to b = a; if (strcmp (b, a) == 0) / / Compare A and B, cannot use IF (b = a);
/ / Pointer
INT LEN = Strlen (a); char * p = (char *) malloc (sizeof (char) * (len 1)); struffpy (p, a); if (strcmp (p, a) == 0)
Three different memory capacity
Use operator SIZEOF to calculate the capacity of the array (number of bytes). In the example, the value of SIZEOF (A) is 12 (note
It is, forgetting '/ 0'). Pointer P pointing A, but the value of SizeOf (p) is 4. This is because SizeOf (P) is obtained.
Is the number of bytes of a pointer variable, equivalent to sizeof (char *), not the memory capacity referred to in P. C / C language
There is no way to know the memory capacity referred to by the pointer unless you remember it when you apply for memory. (How to apply
Remember it? ? ? ? ? )
Note that when the array is passed as a parameter of the function, the array automatically degenerates into the same type of pointer. In the example, no
The capacity of array A is much, and SIZEOF (A) is always equal to SIZEOF (Char *).
Char a [] = "Hello World"; char * p = a;
COUT << SizeOf (a) << endl; // is displayed as 12cout << SizeOf (P) << Endl; // Show to 4 ◎ ◎ ◎ ◎ ◎ ◎ ◎ ◎ ◎ ◎ ◎ ◎
Void Func (Char a [100]) {cout << SizeOf (a) << endl; // is displayed to 4 instead of 100 bytes, array degradation is a pointer
}
*********************************************************** ******************** How does the pointer parameter pass memory? If the parameter of the function is a pointer, do not expect to use the pointer to apply for dynamic memory. Example 7-4-1
The statement of the TEST function GetMemory (STR, 200) did not make Str to get the desired memory, STR is still null,
why?
Void getMemory (Char * p, int Num)
{
P = (char *) malloc (sizeof (char) * NUM);
} Void test (void)
{
CHAR * STR = NULL;
GetMemory (STR, 100); // Str Still null
STRCPY (STR, "Hello"); // Run error
}
Example 7-4-1 Attempt to apply for dynamic memory with pointer parameters
The problem is in the function GetMemory. The compiler always makes a temporary copy for each parameter of the function, pointer parameter P
The copy is _P, the compiler makes _p = P. If the program in the function is modified, the parameter P is caused.
Content makes corresponding modifications. This is why the pointer can be used as an output parameter. In this example, _p applies for new
Save, just changing the memory address referred to _P, but P is unchanged. So the function getMemory does not output anything. In fact, every time GetMemory will disclose a memory, because it is not used to release memory
.
If you have to apply for memory with a pointer parameter, you should use the "pointer to the pointer", see Examples 7-4-2.
Void getMemory2 (char ** p, int Num)
{
* p = (char *) malloc (sizeof (char) * NUM);
} Void test2 (void)
{
CHAR * STR = NULL;
GetMemory2 (& STR, 100); // Note Parameters is & Str, not STR
STRCPY (STR, "Hello");
COUT << str << endl;
Free (STR);
}
Example 7-4-2 Apply Dynamic Memory with a pointer to a pointer
Due to the concept of "pointing pointer" is not easy to understand, we can use functions to return the value to pass dynamic memory
. This method is more simple, see Examples 7-4-3.
Char * getMemory3 (int Num)
{
Char * p = (char *) malloc (sizeof (char) * NUM);
Return P;
} Void test3 (void)
{
CHAR * STR = NULL;
Str = getMemory3 (100);
STRCPY (STR, "Hello");
COUT << str << endl;
Free (STR);
}
Example 7-4-3 Return value with a function to pass dynamic memory
This method is transmitted with a function return value to transmit dynamic memory. Although it is easy to use, someone often uses the returnite sentence.
Here you emphasize not to return to the "stack memory" pointer, because the internal existence of the function is automatically
Examples 7-4-4
Char * getString (Void)
{
Char p [] = "Hello World";
Return P; // The compiler will warn
} Void test4 (void)
{
CHAR * STR = NULL;
Str = getString (); // STR content is garbage
COUT << str << endl;
}
Example 7-4-4 RETURN statement Returns a pointer to "Stack Ins"
Test4 with the debugger, find the Str = getString statement, the Str is no longer a null pointer, but
The content of the STR is not "Hello World" but is rubbish.
If you rewrite the sample 7-4-4, what is it?
Char * getString2 (void)
{
Char * p = "Hello World";
Return P;
} Void test5 (void)
{
CHAR * STR = NULL;
Str = getString2 ();
COUT << str << endl;
}
Example 7-4-5 Return statement Returns a constant string
Although the function test5 is running will not be wrong, the design concept of the function getString2 is wrong. because
"Hello World" in GetString2 is a constant string, located in a static storage area, which is in the program lifetime
Constant. Whenever you call getString2, it returns to the same "read-only" memory block.