C language 02 basic understanding (2)
Pointer Basics
Variable Review
Since the variables in the program are just the alias of a bucket
Can I use this bucket only by using this alias?
Pointer nature
? Pointers are essentially a variable.
? The pointer needs to occupy a certain amount of memory space.
? The pointer is used to save the value of the memory address.
* Meaning
? When the pointer is declared, * indicates that the declared variable is a pointer.
? When using a pointer, the * sign indicates taking the value in the memory space pointed to by the pointer.
// Pointer declaration:
Int I = 0;
Int j = 0;
Int * p = & I;
// Value:
J = * p;
P: 0xAABBCCD0 I: 0
0xAABBCCD0
* Is similar to a key. You can use this key.
Open the memory and read the value in the memory.
1. memory space occupied by pointers
2. pointer address
3. Write memory using the * sign
Value Transfer and address transfer
? The pointer is a variable, so you can declare the pointer parameter.
? When a function body needs to change the value of the real parameter, you need to use the pointer parameter.
? When the function is called, the real parameter value will be copied to the form parameter.
? Pointers are applicable to functions with complex data types as parameters.
Constants and pointers (determine whether const modifies p or * p)
? Const int * p; // p variable. The content pointed to by p cannot be changed.
? Int const * p; // p variable. The content pointed to by p cannot be changed.
? Int * const p; // p is unchangeable, And the content pointed to by p is variable.
? Const int * const p; // The content pointed to by p and p cannot be changed.
Tip: left and right fingers
When const appears on the left of **, the data pointed to by the pointer is a constant.
When const appears on the right side of **, the pointer itself is a constant.
Www.enjoylinux.cn
Pointer Summary
? Pointer is a special variable in C language.
? The value saved by the pointer is the memory address.
? You can use a pointer to modify any address in the memory.
Int * p
0x00eaff00 10 ...... ...... ......
0x00eaff00 basic array Concept
An array is an ordered set of variables of the same type.
Int a [5];
A Indicates the starting address of the first element of the array.
The name of the 20 bytes is
A. A [0], a [1] and so on are all in
Element, not the element name. Quantity
The element in the group has no name.
Each element is int-type data.
Array size
? Array stores elements in a contiguous memory space
? The number of array elements can be displayed or implicitly specified.
Array address and array name
? The array name represents the address of the first element of the array. It is a constant (integer). Therefore, it cannot be used as the left value.
? The address of the array needs to be obtained with the get URL &
? The address value of the element at the beginning of the array is the same as the address value of the array.
? The address of the first element of the array is different from the address of the array.
Your building and your GPS address are
Are they the same, but do they have the same meaning?
Blind spots of array names
? The array name can be seen as a constant pointer.
? The array name points to the starting position of the first element in the memory array.
? In an expression, the array name can only be used as the right value.
? The array name cannot be regarded as a constant pointer only in the following cases.
? Array name as a parameter of the sizeof Operator
? Array name as & operator Parameter
Array Summary
? An array is a continuous memory space.
? The address of the array and the address of the first element of the array have different meanings.
? Array names are treated as constant pointers in most cases.
? The array name is not a pointer and cannot be confused during external declaration.
Obfuscation of concepts is one of the root causes of bugs!
Array and Pointer Analysis
The essence of Arrays
? An array is a continuous memory space.
? The size of the array space is sizeof (array_type) * array_size
? The array name can be seen as a constant pointer to the first element of the array.
Pointer operation
? Pointer is a special variable, and the arithmetic rule for integers is
P + n ;?? (Unsigned int) p + n * sizeof (* p );
Conclusion:
When the pointer p points to an element of the same type of array: p + 1 points
The next element of the current element. p-1 points to the previous element of the current element.
Elements.
Pointer operation
? Only the subtraction operation is supported between pointers, and the pointer type must be involved in the operation.
Must be the same
P1-p2; (unsigned int) p1-(unsigned int) p2)/sizeof (type );
Note:
? Only when two pointers point to elements in the same Array
Subtraction makes sense. It means the subscript difference of the element indicated by the pointer.
? When the elements pointed to by two pointers are not in the same array
Undefined
Pointer comparison
? Pointers can also be used for relational operations.
<=> =
? The prerequisite for pointer relationship calculation is to point to the elements in the same array at the same time.
? Comparison between any two pointers (= ,! =) Unlimited
Array access
? Access the elements in the array in the form of a base object
? Access elements in the array as pointers
Subscript VS pointer
? Theoretically, when the pointer moves in the array with a fixed increment, its effect
Code generated higher than subscript
? Better performance when the pointer increment is 1 and the hardware has a hardware Increment Model
Note:
The optimization rate of Generation Code of modern compilers has been greatly improved, increasing
The efficiency of the subscript form is equal to that of the pointer form.
From the perspective of reading and code maintenance, the subscript format is better.
Differences between a and
? A is the address of the first element of the array.
? & A is the address of the entire array
? The difference between a and & a lies in Pointer operations.
A + 1 (unsigned int) a + sizeof (*)
& A + 1 (unsigned int) (& a) + sizeof (* &)
Array parameters
? In C, when arrays are used as function parameters, the compiler
It is compiled into the corresponding pointer
Void f (int a []);? Void f (int * );
Void f (int a [5]);? Void f (int * );
Conclusion:
Generally, when the defined function contains an array parameter
To indicate the size of the array.
Comparison between pointers and Arrays
? When an array is declared, the compiler automatically allocates a continuous memory space.
? Only the 4-byte space used to hold the pointer is allocated during pointer declaration.
? When used as function parameters, array parameters are equivalent to pointer parameters.
? In most cases, the array name can be regarded as a constant pointer and its value cannot be changed.
? The essence of a pointer is a variable. The stored value is considered as the address in the memory.
What are the strings in C? Conceptually, the C language does not have a string data type.
? Use character arrays in C to simulate strings
? The string in C is an array of characters ending with '\ 0'.
? Strings in C can be allocated to stack space, heap space, or read-only storage zone.
String Length
? The length of a string is the number of characters contained in the string.
? The string length in C indicates the number of characters before the first '\ 0' character.
? In C, the '\ 0' Terminator is used to determine the length of a string.
The return value of strlen is defined by an unsigned number. Therefore
Subtraction cannot generate negative numbers. The preceding statements are not equivalent.
? Generally, do not compile functions provided by the C standard library.
? The standard library is sometimes implemented using an assembly language to make full use of the special commands provided by machines for maximum speed.
? Reusing existing function libraries is more efficient.
Unrestricted string functions
? Unrestricted string functions are used to find the string Terminator.
'\ 0' to determine the length
String replication ::
Char * strcpy (char * dst, const char * src );
String connection ::
Char * strcat (char * dst, const char * src );
String comparison:
Int strcmp (const char * s1, const char * s2 );
? Unrestricted string functions are marked with '\ 0' as the end.
Therefore, the input parameter must contain '\ 0 '.
? Strcpy and strcat must ensure sufficient space in the target character array.
To save the entire source string.
? Strcmp uses 0 to indicate that the two strings are equal.
? When the first string is greater than the second string, the return value is greater than 0.
? When the first string is smaller than the second string, the return value is less than 0.
? Strcmp does not modify the parameter value, but still uses '\ 0 0' as the end character.
String functions with limited length
? A string function with limited length receives a display length parameter
Number of characters allowed for the operation
String replication ::
Char * strncpy (char * dst, const char * src, size_t len );
String connection ::
Char * strncat (char * dst, const char * src, size_t len );
String comparison:
Int strncmp (const char * s1, const char * s2, size_t len );
? Strncpy only copies len characters to the target string
? When the length of the source string is less than len, the remaining space is filled with '\ 0.
? When the source string length is greater than len, only len characters will be copied, and
It will not end with '\ 0.
? Strncat can copy a maximum of len characters from the source string to the target string.
? Strncat always adds '\ 0' after the result string'
? Strncat does not use '\ 0' to fill the remaining space in the target string.
? Strncmp only compares len characters for Equality
Pointer array and array Pointer Analysis
Array represents the address of the first element of the array. What does matrix represent?
The address values of array and & array are the same, but they have different meanings.
Are pointer types the same?
? Rename an array by using typedef in C
Typedef type (name) [size];
? Array type:
Typedef int (AINT5) [5];
Typedef float (AFLOAT10) [10];
? Array definition:
AINT5 iArray;
AFLOAT10 fArray;
Array pointer
? The array pointer is used to point to an array.
? The array name is the starting address of the first element of the array, but it is not the starting address of the array.
? You can obtain the starting address of the array by applying the get URL & to the array name.
? The array pointer can be defined through the array type: ArrayType * pointer;
? You can also directly define: type (* pointer) [n];
? Pointer is the name of the array pointer variable.
? Type is the type of the array to which the object is directed
Pointer Array
? A pointer array is a common array.
? Each element in the pointer array is a pointer.
? Pointer array definition: type * pArray [n];
? Type * indicates the type of each element in the array.
? PArray is the array name.
? N is the array size.
Float * a [3]
Float *
Float *
Float *
Main function parameters
Int main ()
Int main (int argc)
Int main (int argc, char * argv [])
Int main (int argc, char * argv [], char * env [])
Argc-Number of command line parameters
Argv-command line parameter Array
Env-environment variable array
? The main function can be understood as a function called by the operating system.
? When executing the program, you can pass parameters to the main function.
Summary
? An array pointer is essentially a pointer.
? The array Pointer Points to an array address.
? A pointer array is essentially an array.
? The type of each element in the pointer array is pointer.
What are the pointers of multi-dimensional arrays and multi-dimensional pointers to pointers? The pointer variable occupies a certain amount of space in the memory.
? You can define a pointer to save the address value of the pointer variable.
Pointer to pointer
? Why do we need a pointer to a pointer?
? Pointers are essentially variables.
? For pointers, value passing and address passing are also called.
Two-dimensional array and second-level pointer
? Two-dimensional arrays are arranged in one dimension in the memory.
? The first dimension in a two-dimensional array is a one-dimensional array.
? The second dimension in the two-dimensional array is the specific value.
? The array name of a two-dimensional array can be seen as a constant pointer.
Int a [3] [3]
A [0]
A [1]
A [2]
Array name
? The name of a one-dimensional array represents the address of the first element of the array.
Int a [5]? The type of a is int *
? The two-dimensional array name also represents the address of the first element of the array.
Int m [2] [5]? The m type is int (*) [5].
Conclusion:
1. The two-dimensional array name can be seen as a constant pointer to the array.
. 2. Two-dimensional arrays can be viewed as one-dimensional arrays.
. 3. Each element in a two-dimensional array is a one-dimensional array of the same type.
How to dynamically apply for a two-dimensional array
Two-dimensional pointer Simulation
Summary
In C, only one-dimensional arrays are available, and the array size must be
The compilation period is determined as a constant.
The array element in C is any type of data, that is
The element of the array can be another array.
In C, only the size of the array and the address of the first element of the array are available.
Is determined by the compiler directly
Array parameter and pointer Parameter Analysis
Significance of degradation
In C, parameters are transmitted only by copying values.
? When an array is passed to a function
? Copy the entire array and input it to the function.
? Returns the address of the first element of the array as a constant pointer.
C language is designed with efficiency as its initial goal.
If you copy the entire array, the execution efficiency will be greatly reduced.
Two-dimensional array parameters
? Two-dimensional array parameters also have degradation problems
? A two-dimensional array can be viewed as a one-dimensional array.
? Each element in a two-dimensional array is a one-dimensional array.
? The first dimension parameter in two-dimensional array parameters can be omitted.
Void f (int a [5]);? Void f (int a []);? Void f (int * );
Void g (int a [3] [3]);? Void g (int a [] [3]) ;?? Void g (int (* a) [3]);
Equivalence relationship
Array pointer: char (* a) [4] Two-dimensional array: char a [3] [4]
Pointer: int ** a pointer array: int * a [5]
Pointer: float * a one-dimensional array: float a [5]
Equivalent pointer parameter array parameter
Notes
In C language, an arbitrary multi-dimensional array cannot be passed to a function.
To provide correct pointer operations
Length limit of all dimensions
One-dimensional array parameters-the length of an array ending position must be provided
Two-dimensional array parameters-cannot be passed directly to Functions
3D or more multi-dimensional array parameters-unavailable
Function and Pointer Analysis Function Type
? Functions in C language have their own specific types.
? The function type is determined by the return value, parameter type, and number of parameters.
For example, int add (int I, int j) is of the int (int, int) type)
? Rename a function type using typedef in C
Typedef type name (parameter list)
? Example:
Typedef int f (int, int );
Typedef void p (int );
Function pointer
? The function pointer is used to point to a function.
? The function name is the entry address of the execution function body.
? Function pointer can be defined by function type: FuncType * pointer;
? You can also directly define: type (* pointer) (parameter list );
? Pointer is the name of the function pointer variable.
? Type is the type of the return value pointing to the function.
? Parameter list is a list of parameter types pointing to functions.
Callback function? Callback functions are called using function pointers.
? Callback mechanism Principle
? The caller does not know the specific function to be called when a specific event occurs.
? The called function does not know when it will be called, but only knows the tasks to be completed after it is called.
? When a specific event occurs, the caller calls a specific function through the function pointer.
? Callback separates callers from called functions.
Pointer reading skills? Right left rule
1. Starting from the undefined identifier in the parentheses in the innermost layer
2. First look to the right and then to the left
3. When you encounter parentheses or square brackets, you can determine the part type,
And adjust the direction
4. Repeat steps 2 and 3 until the reading is complete.
# Include
Int main ()
{
Int (* p2) (int *, int (* f) (int *));
Int (* p3 [5]) (int *);
Int (* p4) [5]) (int *);
Int (* p5) (int *) [5];
}
Why dynamic memory allocation
All operations in C language are based on memory
Both variables and arrays are memory aliases.
The interpreter is determined during compilation
Specify the length of an array when defining an array.
The array length must be determined during compilation.
Malloc and free
? Malloc and free are used to execute dynamic memory allocation and release
? Malloc is allocated with a continuous memory in bytes,
Without any type information
? Free is used to return dynamic memory to the system.
Void * malloc (size_t size );
Void free (void * pointer );
Note:
? The actual memory allocated by malloc may be slightly more than the requested memory, but not
This behavior depends on the compiler.
? Malloc returns NULL when the requested dynamic memory cannot meet
? When the free parameter is NULL, the function directly returns
Calloc and realloc
? Do you know the malloc brother?
Void * calloc (size_t num, size_t size );
Void * realloc (void * pointer, size_t new_size );
? The calloc parameter indicates the type information of the returned memory.
? Calloc initializes the returned memory to 0.
? Realloc is used to modify the size of a previously allocated memory block.
? The return value should be used after realloc is used.
? When the first parameter of pointer is NULL, it is equivalent to malloc.
Summary
? Dynamic memory allocation is a powerful function in C.
? The program can use more memory as needed
? Malloc simply requests a fixed byte memory from the system
? Calloc can apply for memory in the unit of type size and initialize it to 0
? Realloc is used to reset the memory size.
Stack in the program
? Stack is one of the most important concepts in modern computer programs.
? The stack is used in the program to maintain the context of the function call.
Function, without local variables
? Stack stores the maintenance information required for a function call.
? Function parameters, function return address
? Local variable
? Function call context
Heap in the program
? Why does stack need to be heap?
? The data on the stack will be released after the function returns and cannot be passed out of the function.
For example, partial array
? Heap is a huge memory space in the program and can be freely used by the program.
? The internal application applied by the program in the heap will remain valid until the program is released.
The heap space can be obtained only after application!
? How the system manages heap Space
? Idle linked list method, bitmap method, Object pool method, etc.
Static storage area in the program
? The static storage area of the program allocates space as the program runs until
End of sequential operation
? The size of the static storage area has been determined during the compilation period of the program.
? The static storage area of the program is mainly used to save global variables and
Static variables
? Unlike stacks and stacks, static storage zone information is stored to the executable
In the program
Summary
? Stack, heap, and static storage areas are the three basic memory areas commonly used by C language programs.
? The stack zone is mainly used for function calls.
? The heap zone is mainly used for dynamic memory application and return.
? The static storage area is used to save global variables and static variable wild pointers and Memory Operation Analysis.
? The wild pointer is usually caused by the fact that the value saved in the pointer variable is not a valid memory address.
? The wild pointer is not a NULL pointer, but a pointer to the unavailable memory.
? NULL Pointer is not easy to use, because the if statement is good at judging a pointer
Is it NULL?
In C language, there is no way to determine whether a pointer is a wild pointer!
? The local pointer variable is not initialized.
? Use the released pointer
? The variable pointed to by the pointer is destroyed before the pointer.
Illegal Memory Operation Analysis
? Struct member pointer not initialized
? Not allocate enough memory for the struct pointer
Memory initialization Analysis
? Memory Allocation successful, but not initialized
Memory out-of-bounds Analysis
? Array out-of-bounds
Memory leakage analysis
Multiple pointer releases
Use released pointer
? After applying for memory with malloc, check the pointer value immediately
Is NULL to prevent NULL pointer
? Keep in mind the length of the array and avoid array out-of-bounds operations. use flexibility
Array
? Dynamic Application must match the release operation to prevent memory leakage and
Multiple releases
? The value must be NULL immediately after the free pointer.
Recognize the true face of a function? Origins of functions
Sequencing program = Data + Algorithm
C-order program = Data + Function
Function meaning
? Modular Program Design
Process-oriented programming
? Process-oriented is a process-centric programming idea.
? First, the complex problems are divided into easy-to-solve problems.
? The resolved problems can be solved step by step.
? Function is the embodiment of process-oriented in C Language
? Each step to solve the problem can be implemented using functions.
Description and definition
? The statement in the program can be understood as notifying the compiler entity in advance
In, such as: variables, functions, and so on
? The definition in the program clearly indicates the meaning of the compiler entity
The declaration and definition are different !!!
Function Parameters
Function parameters are essentially the same as local variables. Are space allocated on the stack? The initial value of a function parameter is the real parameter value during function calling.
The order in which function parameters are evaluated depends on the implementation of the compiler !!
In C, most operators calculate the order of their operands.
The order is dependent on the implementation of the compiler !!!
Int I = f () * g ();
What are the order points in the program? There are certain sequence points in the program
? The order point refers to the latest time when the value is modified during execution.
? When the program reaches the sequence point, all previous operations must be reflected.
To subsequent access
? When each complete expression ends
? &, | ,? :, And after each calculation object of the comma expression is calculated
? After the evaluation of all the actual parameters in the function call is completed (before entering the function body)
Default Function Identification
? C language will default function parameters of no type to int
Summary
? C is a process-oriented language.
? Functions can be understood as steps to solve the problem
? There is no fixed calculation order for the real parameters of the function.
? The sequence point is the latest time for variable change in C.
? The default types of parameters and return values in function definition are int function recursion and function design techniques recursion Overview
? Recursion is the application of concepts in mathematics in programming.
? Recursion is a powerful programming method.
? The essence of recursion is that a function calls itself when appropriate.
Recursive functions
? C recursive functions have two main components:
? Point recursion point-call itself with different parameters
? Exit-not recursively called
F (x) =
1; x = 1
X * f (x-1); x> 1
Summary
? Recursive functions in C must use judgment statements.
? A recursive function defines the exit of a function when it needs to be written. Otherwise
Stack Overflow
? Recursive functions are a divide-and-conquer concept.
Function design skills
? Do not use global variables in a function. Try to make the function
Independent function modules
? Parameter names must reflect the meaning of parameters
Void str_copy (char * str1, char * str2 );
Void str_copy (char * str_dest, char * str_src );
Function design skills
? If the parameter is a pointer and only used as the input parameter, add
Const to prevent the pointer from being accidentally modified in the function body
Void str_copy (char * str_dest, const char * str_src );
Function design skills
? Do not omit the type of the returned value. If the function does not return the value
It should be declared as void type
? Check the parameter validity at the "ENTRANCE" of the function body
Pointer check is particularly important
? The statement cannot return a "pointer" pointing to "stack memory" because
The function body is automatically destroyed when it ends.
Function design skills
? The size of the function body should be small and should be controlled within 80 lines of code as much as possible.
? The same input should generate the same output, and try to avoid the function with "NOTE"
Recall "Function
? Avoid too many parameters in a function, and limit the number of parameters to four.
Function design skills
? Sometimes a function does not need to return values, but to increase flexibility, such as supporting chained expressions, you can
Return Value with additional
Char s [64];
Int len = strlen (strcpy (s, "android "));
The function name and return value type cannot conflict in semantics.
Char c;
C = getchar ();
If (EOF = c)
{
//...
}