The sixth chapter uses the array to process data in batches
An array is a set of ordered data that each of the elements in the array belongs to the same data type.
is a kind of data organization structure. The initial structure is the clue.
One-dimensional arrays
Defined:
Type-character array-name [constant-expression] array-name-naming compliance-identifier-naming rules
The size of the array is not allowed to be dynamically defined in the C language.
Description: If an array is defined in the called function, its length can be either a variable or a very-mass expression. The actual argument. This condition is known as a variable-length array. This method is not valid if the array is specified as a static storage mode.
Reference: array name [subscript] subscript is a constant or constant expression ordinal starting from 0.
Initialize: Initialize list int a[5]={1,2,3,4,5}; Looping statements
An element that is not initialized by the initialization list, automatically 0 (character ' \ s ', the pointer is null)
Two-dimensional arrays
A two-dimensional array is often called a matrix. Can be viewed as a matrix, or as a one-dimensional array of elements.
Definition: type character array name [constant expression] [constant expression] rows and columns are stored by row.
Reference: array name [integer expression] [integer expression] row and column numbers are counted from 0
Initialize: Take advantage of initialization list a[2][3]={{},{}}; a[][3]={};a[][3]={{},{}}; Automatic calculation, the number of columns must be written
Multidimensional array case analogy.
Array of character types
The C language does not have string types, and strings are implemented by arrays.
Definition: char a[10]; If you use int a[10]; legal but wasted space.
Initialization: The initialization list is not assigned to '/' empty ' as a space can be manually added ' to ', easy to handle
string constant Initial method char a[]={"I am a student!"};
The string is automatically prefixed with the string end flag '
Character array input and output:
scanf ("%s", c); Enter when a space is encountered or a carriage return ends and the '% ' system treats the space as a delimiter of a string.
printf ("%s", c); Output string before the first ' + '
String handling functions
Puts (character array name) wraps the string after it has finished outputting.
Get (character array name) input string to character array and return array first address
strcat (character array 1, character array 2); Array 1 must be large enough to accommodate the return array 1 address
strcpy (character array 1, character array 2 (string)), copy, 1 length not less than 2, including ' + '
strncpy (str1,str2,2); Partial copy, specify the number of overrides, do not include '/'
strcmp (String 1, string 2); Equal return 0,1>2 returns positive, negative
From left to right ASCII code comparison
strlen (character array); return string length
The second chapter uses the function to realize the scale programming
Each function implements a specific function, and the function name should reflect the function it represents.
A C program consists of one or more program modules, each program module as a source program file. Easy to write and compile separately, improve debugging efficiency. A source file can be pooled for multiple programs.
A source program file consists of one or more functions and related content (directives, data declarations, definitions, etc.). A source file is a compilation unit.
C program execution starts with the main function. All functions are parallel, cannot be nested, only called, and the main function can only be called by the operating system.
Defining functions
No parameter type name Function name (void (or empty))
{
function body (Declaration part, statement part)
}
Parameter type name function name (formal parameter list)
{
function body
}
Empty function type name Function name () {}
Calling functions
Function name (argument list);
Invocation form: Function Call statement, function expression, function argument
Data passing at invocation: arguments can be variables, constants, expressions, arguments assigned to parameters when invoked, and arguments and formal parameter types should be identical or assignment compatible. (Automatic conversion)
The parameter storage unit is temporarily allocated, and the cell is freed after the call ends. Value is passed, and the argument is not changed after the end.
return (variable constant expression);
function declarations and function prototypes
Library functions: Use #include<> to include information about library functions in a file. (Library function Declaration)
Custom functions: Function declarations
Function prototypes are the first line of function definitions, and C functions are declared with function prototypes. You can omit formal parameters when writing function declarations. Write formal parameters to facilitate comprehension of functions.
If the declaration is written at the beginning of the file (before all functions), it does not have to be declared in its function. Valid throughout the file scope.
Nested calls to functions
Functions are not nested defined, but can be nested calls. That is, use other functions in the way that they are called in the function definition.
recursive invocation of functions
Call the function itself directly or indirectly.
Array as function parameter
An array element can be used as a function argument, with the same usage as the variable, passing the value of the array element to the parameter.
Array elements cannot be used as formal parameters.
An array name can also be an argument and a parameter, passing the address of the first element of the array.
When using an array name function argument, the first element address of the array is passed to the formal parameter (array or pointer variable).
function as defined: float average (float array[10]) (c Compile system does not check the size of the shape parameter group)
{} can not add 10
Called when float score[10]; Ave=average (score);
Address Pass, add subscript, read the storage unit sequentially, the operation of the formal parameter is the operation of the argument
You can use a multidimensional array name to do the arguments and parameters of a function, and you can omit the first dimension size description when defining the parameter group.
The C compilation system does not check the first dimensional size and can be grasped from the array storage form.
local variables and global variable variable scope problems
Local variables: functions within defined (whole function scope), compound statement defined (compound statement inside) formal parameters
Two local variables with different scopes can have duplicate names. Include compound statement {}
Global variables: Written outside the function, global variables can be shared with other functions in this file, and its valid range is from the location of the defined variable to the end of the source file.
Use global variables to increase the communication channels between functions. General global variable first letter capitalized (not specified)
Do not use global variables when necessary:
Exclusive memory, versatility, low reliability, reduced program clarity (blur)
Local Global variables conflict (duplicate name, scope overlap) local effective global masking.
How variables are stored and their lifetimes
static storage mode (fixed), dynamic storage (on demand)
Memory for users to use storage space: Program area, static storage area, dynamic storage
Global variables are stored in a static storage area.
Dynamic storage: Formal parameters, automatic variables, field protection and return address when function calls, etc.
In C, each variable and function has two properties: the data type and the storage category of the data
Storage categories for local variables:
The automatic variable (auto) function is a local variable, not specifically declared as static storage class, dynamic store. The function is called when it is allocated and is disposed at the end.
Static local variables, declared with the keyword static, do not disappear after the end, the storage unit is reserved. The next call to the function's original value is preserved. Static storage, which is not released while the program is running.
!! The static local variables are assigned the initial value at compile time, only once, the program runs with the initial values, and each time the call is no longer assigned to the initial, but the last time. Automatic variables are assigned at run time, so new values are assigned repeatedly.
Automatic variable does not assign initial value: Unpredictable, because the automatic allocation unit
Static variable does not assign initial value: 0 or ' + '
Use static storage to account for more memory and reduce readability.
Register variable (register)
For the use of frequent variables, directly stored in the CPU register, improve execution efficiency.
register int F; Some compilation systems can automatically identify the optimization transformation.
Storage categories for global variables
Global variables are stored in a static storage area. The lifetime of the entire running process. It mainly studies its scope.
Extend this file: extern declarations (such as function declarations)
Extend to different files: make extern declarations in different files. The compilation system is processed when compiling and connecting.
extern declaration: An external variable declaration that allows an external variable to start at this point.
extern variable name 1, variable name 2, ....
Expanding the scope of global variables should be very cautious, because the fixed storage space, can be arbitrarily modified.
Limit scope static declaration static int A; Static external variables are only valid in this file
The same external variable names can be used in different files without interfering with each other's misuse
Declaring a local variable storage type is to determine its storage and lifetime, whereas the storage type declaration on a global variable is a scope extension issue.
intrinsic and external functions
intrinsic function: static int fun (int a,int b) {} can only be called by other functions in this file
Different files, if they have the same name, also do not interfere
External functions can be called by other files can be omitted extern in other files that need to call this function, you need to declare this function, add the keyword extern to indicate that the function is an external function defined in other files, but generally omit the. h file contains the declaration of all functions in the library
Chapter Three is good at using pointers
Need to be used correctly and flexibly
Accessed directly by the variable name, called Direct access, and accessed indirectly by a variable that holds the address information.
If there is a variable dedicated to the address of another variable, it is called a "pointer variable"
The pointer is an address. Distinguishes between pointers and pointer variables.
pointer variables (able to point to variables, arrays, functions, etc.)
Define type name * Pointer variable name such as int *pointer_1; Can only point to the specified base type
The pointer meaning of a variable includes two aspects, one is the address represented by the storage unit number, and the other is the data type of the storage unit it points to
You can only store addresses in pointer variables, and do not assign an integer to a pointer variable.
Reference Assignment p=&a; *p=1; printf ("%o", p); & Fetch Address operator * pointer operator
Pointer variable as function parameter (address)
Pointer variables allow you to change the value of a variable by calling a function, and you can use these changed values in the keynote function. The call to a function can only get a return value, and with a pointer variable, you can get multiple values that change.
referencing arrays by pointers
The reference array can be subscript (a[i]), or the pointer method (* (A+i)) can also be used. The pointer method can make the program of high quality.
In the C language, the array name represents the first element address in the array. So p=&a[0]; and p=a; equivalence.
P+1 points to the next element, P-1 points to the previous element. is not simple plus 1, related to the base type.
P++,++p,p--,--P also same principle
[] Actually is the variable address operator, which looks for the element by the pointer mechanism. Beyond the array, the C compilation system is unaware.
Pointer variable can be labeled P[i] processing into * (p+i) error prone, less use
P2-p1 relative position
The array name is a pointer constant, not a variable. Not self-added, self-reduction. The array name can be passed as a function parameter for the address.
This method is commonly used to change the value of a real parameter group by invoking a function.
If a pointer variable does an argument, you must first make it a definite value.
referencing multidimensional arrays by pointers * (a+i) a[i] equivalent A[I][J] * (* (a+i) +j) equivalence here must be understood
The two-dimensional array A A is the same as the *a address value, but if A+1 (*a) +1 is different, the stepping is different.
&a[0] is a, do not take &a[i] as the physical address of the a[i] element, because there is no real data storage unit such as A[i]. is only a method of calculating the address.
pointer variables that point to multidimensional array elements can be pointer variables that point to elements, or pointer variables that point to a one-dimensional array of M elements.
int * p; The point is an element if int (*p) [4]; P is a one-dimensional array that points to 4 integral elements, and the base type of pointer p to the array is a one-dimensional array
Using pointers to arrays as function arguments
Real participation parameters If they are pointer types, they should be required to be of the same type, and int * and INT (*) [4] are different types
Arrays and pointers are often closely linked, using proficiency, can improve program quality, more convenient and flexible.
referencing strings by pointers
Char * string= "I am a student"; With Char string[]= "I am a student"; consistent
You can use arrays or pointers to reference strings, and for character elements, subscript or pointer methods are available.
Character pointers as function parameter strings handle character pointers and character array names are variable constants that differ
Using a character pointer variable and a character array comparison
At compile time, a character array is assigned several storage units to hold the values of each element, whereas for a character pointer variable, only one storage unit (VC + + as pointer variable 4 bytes) should be specified immediately after the pointer variable is defined.
The elements of a character array can be changed, but the contents of the string constants that the character pointer variable points to are not replaceable.
The string is stored in memory as an array.
Use a pointer variable to point to a format string, which can be used instead of a format string in printf.
Char * format; format= "a=%d,b=%f\n"; printf (format,a,b);
You can change the input and output format as long as you change the string that the format points to. Variable format output function.
Char format[]= "a=%d,b=%f\n" can also be implemented with character arrays; printf (format,a,b);
When you use a character array, you can only use methods that initialize or assign values to the elements one at a time when you define an array, and you cannot assign values to an assignment statement as a whole (a character pointer variable can).
Pointers to functions
If a function is defined in the program, at compile time, the compilation system allocates a storage space for the function code, and the starting address of the storage space is called a pointer to the function.
Int (*p) (int,int); P points to an integer function that has two integer arguments
int *p (int,int); To define a function that returns a pointer
Calling a function, in addition to being called with a function name, can also be called by a pointer variable pointing to the function.
P=max; (Point to a function that conforms to the defined format, Max is the function name) c= (*p) (A, B);(call function)
The array name is similar to the first element of the arrays, and the function names represent the entry addresses of the functions.
return value type name (* pointer variable name) (parameter list)
Call a function with a function name, only the specified function can be called, and the pointer variable call function is more flexible, you can call different functions according to different circumstances.
Use pointers to functions as function arguments
One important use of pointer variables to a function is to pass the address of the function as a parameter to other functions.
Implement a variable invocation. That is, the function that is called internally can be changed by simply changing the pointer. Increase flexibility.
So you can write some more complex programs.
Functions that return pointer values
Type name * Function name (parameter table column) and one less call function with pointer () should be distinguished
pointer arrays and multiple pointers
An array whose elements are pointer-type data, called an array of pointers.
Type name * array name [array length]
Pointer to pointer data
Type name * * variable name; Two-part understanding of pointer variables pointing to a type of pointer
A pointer array as the formal parameter of the main function
Before general writing int main () in some cases the main function can have the parameter int main (int argc,char *argv[]);
The main function is called by the operating system, and the implementation is given only by the operating system, and in the Operation command, the arguments are given along with the command that executes the file. So like Dos,unix,linux, command line is the general form of the command name parameter 1 parameter 2 ....
Using an array of pointers as the main function parameter, you can pass command-line arguments (these are strings) to the program.
Dynamic memory allocation with pointer variables pointing to it
The C language allows the creation of dynamically allocated areas of memory to hold temporary data, which do not have to be defined in the declaration section of the program, nor should it be released at the end of the function, which needs to be opened up without being released.
Because it is not declared, it cannot be referenced by a variable name or array name, but only by a pointer reference.
Establish dynamic memory allocation
Use the malloc function void *malloc (unsigned int size); A continuous space of size is opened, and a pointer to the non-type specified is returned, pointing to the first address. The assignment did not return null successfully.
Using the Calloc function
Void *calloc (unsigned n,unsigned size); Allocate n contiguous spaces of size in the dynamic storage of memory, which is generally large enough to hold an array. The function returns a pointer to the starting position of the assigned domain, and the assignment does not return null successfully.
The free function
void free (void *p); Releasing P points to the dynamic space P is the return value that was obtained when the last time the Calloc or malloc function was called.
realloc function void *realloc (void *p,unsigned int size); Change the size of the allocated dynamic space
The above four functions are declared in Stdlib.h.
The C99 standard is to set the base type of the above function as void, which is called an untyped pointer, which does not point to a specific type of data, provides only a pure address, and cannot point to any specific object.
void pointer type (C99)
void * Does not point to any definite type of pointer variable that is pure address
When you assign a void pointer to a pointer variable of a different base type, the compilation system automatically converts it. You do not have to cast.
(int *) malloc (); Forced
Dynamic memory allocation is primarily used to establish dynamic data structures in programs.
NULL is defined in the stdio.h file #define NULL 0; You should assign a value to a pointer variable before referencing it.
Advantages of using pointers: to improve the efficiency of the program, you can get multiple values from function call to realize dynamic storage.
The fourth chapter the user establishes the data type
The C language allows the user to create some types of data on their own, and use it to define variables.
Defining and using struct-body variables
The C language allows the user to set up a composite data structure composed of different types, called structs.
declares struct type struct struct body name {member List};
A member can be another struct type.
Define struct-body variables declaration first, and then define the declaration at the same time
Direct definition without specifying a type name (less used)
The member name in the struct type can be the same as the variable name in the program and does not conflict
Initialization and reference of variables
The initialization list is a number of constants enclosed in curly braces.
C99 allows the initialization of a struct Student b={.name= "Zhang Heng" on a member;
System initialization is 0 (\0,null)
Reference member value structure with variable name. member name student.num=10010; Assigning values to members
You cannot attempt to export all of the structure, only input the output to each member individually.
If the member itself is a structure, it can only be layered in depth, only the lowest level of the composition of the assignment and access and operation.
Homogeneous structural variables can be assigned to each other.
You can reference struct member addresses or reference struct variable addresses.
The address of a struct variable is used primarily as a function parameter to pass the address of a struct variable.
Working with struct-body arrays
struct type an array group name [array length];
such as struct person leader[3]; struct struct name {member list} array name [array length];
Struct person leader[3]={"Li", 0, "Zhang", 0, "Sun", 0};
struct-Body pointer
A pointer to a struct object that can point to a struct variable or to an element in a struct array.
Struct student *pt; Base types must be consistent
For convenience and intuition, C language allows (*p). Num to be replaced by a p->num. , is called a pointer operator.
If you want to assign a member address to p, you can use that coercion type conversion.
p= (struct student *) Stu[0].name; The pointing type of p does not change, so p++ points to Stu[1].name's first address.
function parameters with pointers to structural variables and structural variables
The member is the argument, and the value is passed. A struct variable is passed as an actual parameter. A pointer to a struct variable is used as an argument, and the address is passed.
Working with pointers for linked lists
A linked list is a common and important data structure. A structure that dynamically stores allocations. Open the internal deposit cells as needed.
It is most appropriate to use structural variables to create a linked list.
struct student {int num; float score; struct student *next;}; The basic form of a linked list node
Static linked list all the nodes are defined in the program, not temporary open, and can not be exhausted after release. The program is not removed until it finishes running.
The dynamic memory allocation method is used to set up the dynamic link list.
sizeof (); Returns the number of bytes of possession specified by the compilation system rather than the theoretical number of bytes. Remember.
The fields of application of structure and pointers are very broad, besides the one-way linked list, there are also circular linked lists and doubly linked lists. In addition, there are queues, trees, stacks, graphs and other data structures.
Common body Type
A structure that enables several different variables to share the same piece of memory, called a "common body" type structure.
Union common body Name {member list} variable table column; using overlay technology
You can separate the declaration from the definition. is similar to a structural body.
Memory length equals the length of the longest member.
You cannot reference the shared body variable itself, but only its members. A.I a.ch A.F
A store of shared body variables that can hold data in different types.
When using a shared body variable, be aware of which member type is currently stored in the shared storage area.
The shared body variable address is the same address as each member address. &a.i; &a.ch; &a.f;
You cannot assign a value to a shared body variable name, C99 allows the same type of shared body variables to be assigned to each other.
The C99 now allows the use of a common body variable as a function parameter.
A common body type can appear in a struct type definition, or you can define a common body array. Structs can also be present. In a common body type definition, an array can also be a member of a common body.
In data processing, it is sometimes necessary to arrange different uses for the same space.
Using enum types
If a variable has only a few possible values, it can be defined as an enumeration type.
declaring enum type: Enum [enumeration name]{enumeration element list}; The default first element is 0, plus 1 in turn. can also be specified by man.
An enumeration element is treated as a constant, which is an identifier that represents a constant. Each of the enumeration elements represents an integer. Because the value of an enumerated variable is an integer, C99 takes the enumeration type as one of the integral types.
The use of enumerations is to make the program intuitive and convenient.
with typedef declaring a new type name
You can use typedef to specify a new type name instead of an existing type name.
Simply replace the original type name with a new type name
typedef int Integer; Increase program readability.
Name a simple type name instead of a complex type
Complex such as structs, common bodies, enumerations, pointers, arrays, etc., names are lengthy.
By changing the name of the variable to the new type name, and by adding a typedef at the top, the new type name represents the original type, as defined by the variable.
When using the same type of data in different source files, a common typedef declares some data types. You can put all the TypeDef declarations in a single header file, and then call the header file in the file where they are needed. This eliminates the need to define the typedef name yourself in each file.
Make programming convenient, easy to transplant, simple program, easy to read. Program porting only changes the definition body.
Fifth. Input and output of the file
C basic knowledge of the document
Program Files c obj exe and other content is program code
Data file content is not a program but is intended to be read and written by the program runtime
The data input and output processed by the previous chapters depend on the terminal.
A file generally refers to a collection of data stored on an external medium.
In order to simplify the user's operation to the input, so that the user does not have to distinguish between the different devices, the operating system unifies all kinds of equipment as a file to deal with. The terminal keyboard is an input file, and the display and printer are output files.
The operating system manages the data in the file units.
The various files or devices that are input and output are unified in the form of logical data streams.
File ID includes file path filename skeleton file suffix 3 are written out to uniquely identify
Classification of files
Data files can be divided into ASCII files and binary files (image files)
Characters are stored in ASCII format, and numeric data can be stored in both ASCII (input and output) as well as in binary form.
File buffers
A buffered file system is a system that automatically creates a file buffer in the memory area for each file being used in the program. Divided into input file buffer and output file buffer
File Type pointer
Each used file opens up a corresponding file in memory to store the file information. This information is stored in a struct variable. Defined as a file type is often defined to refer to the file information area
FILE *pt; Point to the in-memory file information area beginning with information in the file information area to access the file
Open and Close files
Open the file to create the appropriate information area for the file and buffer (temporarily hold input and output data) pointer variable specified
Closing the file is undoing all of this.
The fopen function opens the data file fopen (filename, using file mode); The return value is a pointer to the file information area.
FILE *FP; Fp=fopen ("A1", "R");
Text file: R Read only (input data) W (output data) write only a append text file end Add data
r+ w+ A +
Binary file: RB read-only input data WB (output data) AB Append
rb+ wb+ ab+ Different compilation system rules may differ
The program can use 3 standard stream files, standard input stream, standard output stream, standard error output stream.
The system automatically opens these 3 standard stream files when the program starts running.
fclose function Close Data file fclose (file pointer);
If you do not close the file will be lost data, but some of the compilation system before the end of the program will automatically write the contents of the buffer to the file, to avoid this problem. After successful execution, Fclose returns 0 and does not successfully return EOF (-1)
Sequential read and write data files
Read and write a character
FGETC (file pointer); Returns the read character or EOF (end-of-file flag)
FPUTC (character variable, file pointer); Exit is the library function of standard C, and the program terminates.
Read and write a string using the Fgets and fputs functions
Read and Write file fprintf and FSCANF functions in a formatted way
To read and write a set of data fread and fwrite functions to a file in a binary way
Random Read and write data files
You can access data from anywhere in the file relative to sequential read and write.
Error detection for file read and write
C Language Notes (Tan version Sixth ~ end)