I. C language helloworld case study:
# Include // Introducing the header file (introducing the function library) is equivalent to the java import operation.
# Include
Main () // main function, similar to the entry function of a java program
{
Printf ("Hello world! \ N "); // output on the console
System ("java cn. itcast. demo. HelloWorld"); // call the java File
System ("pause ");
}
// System ("pause"); yes: Call the pause command in cmd to pause the following execution in the cmd window, so that we can observe the execution result of the program.
Ii. Basic data types of C language:
C Data Type
Char, int, float, double, signed, unsigned, long, short and void
1. In c99 syntax, there is no boolean data type, and true or false. If not 0, true 0 indicates false.
2. There is no byte type in the C language,
How to Make C language represent byte in java? The char type can be used to replace the byte type in java.
3. There is no String in the c language. c indicates that a String is usually represented by a char array.
Sizeof (); the parameter is the return value of the data type, which is the amount of space occupied by the Data Type in the memory.
4. Note: signed and unsigned: only integer data can be modified, not floating-point data.
Signed indicates signed, unsigned indicates unsigned.
5. In java, char is two bytes, one in C.
*/
# Include // Introduce the header file java import Operation
Main ()
{// % D represents a placeholder
Printf ("char occupies % d \ n", sizeof (char); 1 byte
Printf ("int occupies % d \ n", sizeof (int); 4 bytes
Printf ("float occupies % d \ n", sizeof (float); 4 bytes
Printf ("double occupies % d \ n", sizeof (double); 8 bytes
Printf ("short occupies % d \ n", sizeof (short); 2 bytes
Printf ("long occupies % d \ n", sizeof (long ));
Printf ("signed int occupies % d \ n", sizeof (signedint ));
Printf ("the bytes occupied by the unsigned int are % d \ n", sizeof (unsignedint ));
// Printf ("the byte occupied by unsigneddouble is % d \ n", sizeof (unsigned double); this line of code reports an error.
System ("pause ");
}
Iii. Input and Output Functions:
1. The delete operation in C language is implemented using placeholders. Different types of data correspond to different placeholders:
% D-int
% Ld-long int
% C-char
% F-float
% Lf-double
% X-hexadecimal output int, long int, or short int
% O-octal output
% S-string
% Hd-short
Short
2. C Language Input Functions:
Int len;
Scanf ("% d", & len); // scan the keyboard input function:
Parameter 1: A placeholder of the specified type of input data.
Meal 2: Specify the variable address for saving the input value.
Example:
# Include // Introduce the header file java import Operation
Main ()
{
Int I = 129024;
Long l = 333L;
Char c = 'B ';
Float f = 3.1415926f;
Double d = 3.1415;
Short s = 257;
Printf ("int I = % d \ n", I );
Printf ("int l = % ld \ n", l );
Printf ("int c = % d \ n", c );
Printf ("int f = % f \ n", f );
Printf ("int d = % lf \ n", d );
Printf ("short s = % hd \ n", s );
Char cc;
Printf ("enter an int type value \ n ");
// & Obtain the address
Scanf ("% c", & cc );
Printf ("char cc = % c \ n", cc );
// Receives the input string using the char array:
// Define a char array named arr to store strings
Char arr [] = {'','','','',''};
Printf ("enter a string \ n ");
Scanf ("% s", arr );
Printf ("array content % s \ n", arr );
System ("pause ");
}
4. pointer:
1. The so-called pointer is an address, and the address is actually a memory space number.
2. Each variable has an address in the memory: Get the address of the variable through the & symbol.
Example:
# Include
Main (){
Int I;
// Print the address of the I variable in the memory
// Print the address of the variable. The pointer is an address,
// The address is in hexadecimal format: for example, 0 xXXXX, # indicates that the print value is preceded by 0x.
Printf ("I address: % # x \ n", & I );
// 60 seconds countdown
For (I = 60; I> 0 ;){
Printf ("remaining time % d \ n", I );
Sleep (4000 );
I --;
}
Printf ("game ended \ n ");
System ("pause ");
}
3. pointer and pointer variable:
Example:
# Include
Main (){
// 1. the pointer is the address. An address can be used to access a memory space. If you modify the content in the memory space
Int I = 5; // defines the name of an int-type variable named I. The content stored in it is an int-type value.
// 2. the pointer variable is used to store the variable address.
Int * p; // defines the name of a variable of the int * type.
// Int * type value
// It can also be defined as int * p; or int * p;
P = & I; // the address of the I variable is stored in p.
Printf ("the value of p is % # x \ n", p );
// Relationship between pointers and pointer Variables
// The pointer is an address ..
// The pointer variable is the variable that stores an address
// Actually, there are two completely different concepts, but the books in the world are used to no difference between pointers and pointer variables.
// Use the * operator:
1. Use Cases to define a pointer variable int * double * long *
2. Two data are multiplied by 3*5 = 15;
3. If * is followed by a pointer variable, you can use * to access the variable stored in the internal address of the pointer variable.
// * P; // obtain the variable to which the address points in the p variable, that is, the value corresponding to I;
// * P and I represent the same variable.
Printf ("* p value: % d \ n", * p );
System ("pause ");
}
5. Common pointer errors:
1. Pointers cannot be used without being assigned values: the following code reports an error:
# Include
Main (){
Int I = 5;
Int * p;
Printf ("* p value: % d \ n", * p );
System ("pause ");
}
2. Different pointer types cannot be converted to each other.
# Include
/**
Different pointer types cannot be converted to each other.
The memory space occupied by each variable type is different.
*/
Main (){
Short s = 278;
Int I = 2777777; // 4 bytes
Int * p = & I;
Short * q = & I; // short occupies two bytes in the memory space
Printf ("* p = % d \ n", * p );
Printf ("* q = % hd \ n", * q );
System ("pause ");
}
3. Data in the memory space that has been recycled by the system cannot be used:
6. Case: Exchange two numbers.
Data exchange is achieved by modifying the values in the address.
# Include
Void swap2 (int * p, int * q) {// p represents the I address, and q represents the j address.
// The address of the I and j variables is passed to the subfunction. In the subfunction, the value in the address is directly modified to exchange data.
// * P indicates the I variable.
// * Q indicates the j variable.
Int temp;
Temp = * p;
* P = * q;
* Q = temp;
}
// Main method
Main (){
Int I = 3;
Int j = 5;
// Swap (I, j );
Swap2 (& I, & j );
Printf ("I = % d \ n", I );
Printf ("j = % d \ n", j );
System ("pause ");
}
VII. Role of pointers:
1. directly access the hardware (opengl graphics)
2. Fast data transfer (pointer to address)
3. return more than one value (returns a pointer to an array or struct)
For example, modify the values of two variables simultaneously in the subfunction:
# Include
// This is equivalent to letting the sub-function modify the value of a data connection in the main function. The sub-function returns more than one data.
Void f (int * p, int * q) {// p indicates the address of I, and q indicates the address of j.
* P = * p + 3;
* Q = * q + 3;
}
Main (){
Int I = 3;
Int j = 5;
F (& I, & j); // call a subfunction
Printf ("I = % d \ n", I );
Printf ("j = % d \ n", j );
System ("pause ");
}
4. complex data structures)
5. Easy to process strings
// The C language does not have the String type. In the C language, a String is usually represented by a character array.
# Include
Main (){
// Char arr [] = {'h', 'E', 'l', 'l', 'O '};
// Char pointer variable
Char * arr = "hello ";
// Output character Transmission
Printf ("% s \ n", & arr [0]); // The first address of the arr [0] character array.
System ("pause ");
}
6. pointers help you understand object-oriented
8. Relationship between pointers and arrays:
1. array:
An array is a continuous memory space in the memory.
The array name is equal to the address (first address) of the first element in the array ).
Int arr [] = {1, 2, 3, 4 };
Printf ("arr = % # x \ n", arr );
Printf ("the address of the first element is % # x \ n", & arr [0]);
The output values of the above two lines of code are the same.
2. pointer Operation Array:
For example, develop a sub-method to print every element of the array.
# Include
// The first address of the first parameter array and the length of the second parameter Array
Void printArr (int * parr, intlen ){
Int I;
For (I = 0; I
// Output Method 1: Obtain the values in the Array Based on the subscript of the array:
Printf ("arr [% d] = % d \ n", I, parr [I]);
// * Parr // content corresponding to the first element of the array
// * (Parr + 1) obtain the content corresponding to the second element of the array (because the memory is a continuous space)
Printf ("arr [% d] = % d \ n", I, * (parr + I ));
}
}
Main (){
Int arr [] = {1, 2, 4, 5, 6, 7, 8, 9 };
PrintArr (arr, 9 );
System ("pause ");
}
9. pointer operation:
1. pointer operations make sense only for the continuous memory space. arrays are a continuous memory space:
For example, calculation between array element pointers:
# Include
Main (){
// Array is a continuous memory space
Int intarr [] = {1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Int * arr0 = & intarr [0];
Int * arr0 = intarr; // address of the first element of the array
Int * arr1 = & intarr [1];
Int * arr2 = & intarr [2];
Printf ("arr0 address: % # x \ n", arr0 );
Printf ("arr1 address: % # x \ n", arr1 );
Printf ("arr2 address: % # x \ n", arr2 );
Printf ("the distance between arr2 and arr0 is % d \ n", arr2-arr0 );
// The result of the subtraction and addition of pointer operations is actually the offset of the memory address, not the result of the addition and subtraction of memory address integers. the result indicates the offset between several memory spaces.
Char chararr [] = {'1', '2', '3', '4', '5 '};
// Int * arr0 = & intarr [0];
Char * chararr0 = chararr; // address of the first element of the array
Char * chararr1 = & chararr [1];
Char * chararr2 = & chararr [2];
Printf ("chararr0 address: % # x \ n", chararr0 );
Printf ("chararr1 address: % # x \ n", chararr1 );
Printf ("chararr2 address: % # x \ n", chararr2 );
Printf ("the distance between chararr2 and chararr0 is % d \ n", chararr2-chararr0 );
System ("pause ");
}
9. pointer length:
# Include
Main (){
// On a 32-bit operating system, the 2's 32-power memory address is 4 bytes
// The devcpp tool used on my current 32 computer operating system, gcc
Int I = 3;
Int * ip = & I;
Double d = 3.14159;
Double * dp = & d;
Float f = 6.28f;
Float * fp = & f;
Short s = 255;
Short * sp = & s;
// The pointer length is 4.
Printf ("int pointer length: % d \ n", sizeof (ip ));
Printf ("double pointer length: % d \ n", sizeof (dp ));
Printf ("float pointer length: % d \ n", sizeof (fp ));
Printf ("short pointer length: % d \ n", sizeof (sp ));
System ("pause ");
}
10. dynamic memory and static memory:
1. dynamic memory
A non-sequential memory space created in the heap space can occupy all the memory of the entire operating system.
Heap memory is the remaining memory space maintained by the operating system,
All the new objects in java are allocated to the heap memory.
In the C language, apply for heap memory space to use the malloc function.
The malloc function accepts a parameter that represents the amount of memory space dynamically applied in the heap memory.
The return value of malloc indicates the first address of the applied memory space.
Use the free (intp) function to release heap memory and mark the heap memory as available.
Example: Apply for heap memory space:
# Include
// Introduce the dynamic memory allocation header file
# Include
F (int ** padress ){
// * Padress obtains the p variable in the main function.
// The size of the requested memory space is 8 bytes. The first address of the space is assigned to the intp variable.
Int * intp = (int *) malloc (sizeof (int) * 2 );
* Intp = 33; // put an int type value in the space requested by the heap memory to 33
* (Intp + 1) = 99 ;//
* Padress = intp; // assign the heap memory address to the p variable in the main function.
// Free (intp); // release the heap memory space and mark the heap memory as available.
Printf ("subfunction I address: % # X \ n", intp );
}
Main (){
Int * p; // The address used to store the I variable in the subfunction.
// Int-> int *-> int **
// Obtain the address of the I variable of the subfunction in the main function.
F (& p );
// Manually reclaim the applied memory space
Free (p); // residual image in 99 memory, or phantom
Printf ("main function I address % # X \ n", p );
Printf ("the main function I value is % d \ n", * p );
Printf ("the second value of the main function is % d \ n", * (p + 1 ));
System ("pause ");
}
2. Static Memory is created on the stack space with a continuous memory space of 2 MB.
3. Advantages of dynamic memory:
Dynamic memory can be used across functions, but static functions cannot.
The length of the array in the dynamic memory can be dynamically increased or reduced in the function running.
Dynamically add array length: Use the reallco function.
For example, add the array length dynamically: Use the reallco function:
# Include
// Introduce the dynamic memory allocation header file
# Include
Void printArr (int * arr, intlen ){
Int I;
For (I = 0; I
Printf ("student ID % d score: % d \ n", I, arr [I]);
}
}
Main (){
Printf ("Enter the total number of students \ n ");
Int len;
Scanf ("% d", & len );
// Dynamically create an Array Based on len
Int * pgrade = malloc (sizeof (int) * len );
Int I;
For (I = 0; I
Printf ("Enter student % d Score \ n", I );
Scanf ("% d", (pgrade + I ));
}
Printf ("Print Student Score list \ n ");
PrintArr (pgrade, len );
Printf ("Enter the number of students to be added \ n ");
Int addnumber;
Scanf ("% d", & addnumber );
Pgrade = realloc (pgrade, sizeof (int) * (len + addnumber ));
Int j;
For (j = len; j <(len + addnumber); j ++ ){
Printf ("Enter the new student % d Score \ n", j );
Scanf ("% d", (pgrade + j ));
}
Printf ("re-print Student Score list \ n ");
PrintArr (pgrade, len + addnumber );
System ("pause ");
}
11. Differences between heap and stack:
1. Application Method
STACK:
Automatically assigned by the system. for example, declare a local variable int B; the system automatically opens up space for B in the stack. for example, the variable to be saved when calling the Han number, the most obvious thing is that in recursive calls, the system needs to automatically allocate a stack space, first in, first out, then the system releases the space.
Heap:
The programmer must apply and specify the size. Use the malloc function in c.
For example, char * p1 = (char *) malloc (10 );
But note that p1 is in the stack.
2. system response after application
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.
3. Application size limit
STACK: in Windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (which can be set in vc compilation options, it is actually a STACK parameter, 2 MB by default). If the applied space exceeds the remaining space of the STACK, overflow will be prompted. Therefore, the space available from the stack is small.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.
4. Comparison of application efficiency:
STACK: the stack is automatically allocated by the system, and the speed is fast. But programmers cannot control it.
Heap: Memory allocated by malloc/new is generally slow and prone to memory fragmentation, but it is most convenient to use.
5. Storage content in heap and stack
STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.
When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.
Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.
6. memory recovery
Memory allocated on the stack will be automatically withdrawn by the compiler. The memory allocated on the stack should be explicitly withdrawn through free; otherwise, memory leakage will occur.
The difference between stack and stack can be seen in the following metaphor:
Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.
Using heap is like making your favorite dishes by yourself. It is troublesome, but it suits your taste and has a high degree of freedom.
12. java value transfer and reference transfer:
Public StringgetPersonName (Person p ){
Return person. getName ();
}
The p variable stores the address of the person object in the heap memory. (value). // It feels that java only supports value transfer.
The p variable represents a reference of the person object, which is passed by reference.
13. Multilevel pointers:
For example, use r to get the I value:
# Include
Main (){
Int I = 3;
Int * p = & I;
Int ** q = & p;
Int *** r = & q;
// Obtain the I value
Printf ("I = % d \ n", *** r );
System ("pause ");
}
13. function pointer:
Obtain the first address of the function. You can use the first address to execute the function.
Example:
# Include
/**
1. Define int (* pf) (int x, int y );
2. Assign pf = add;
3. Reference pf (3, 5 );
*/
Int add (int x, int y ){
Return x + y;
}
Main (){
Int (* pf) (int x, int y); // defines the pointer type of a function. The return value is the int accepted parameter.
Pf = add;
Printf ("result = % d \ n", pf (3,6 ));
System ("pause ");
}
14. struct: use struct to define struct:
# Include
// Define a struct
Struct Student
{
Char sex; // 1
Int age; // 4
Float score; // 4
Int id; // 4
};
Main (){
//
Struct Student st = {80, 55.6f, 10000, 'F '};
// Obtain the pointer of the struct.
Struct Student * pst = & st;
Printf ("age = % d \ n", st. age );
// Struct Length
Printf ("struct length % d \ n", sizeof (st ));
// Obtain the variable in the struct using a pointer
Printf ("age = % d \ n", (* pst). age );
// Use the pointer to obtain the second method of variable in the struct:
Printf ("age = % d \ n", pst-> age );
System ("pause ");
}
14. Consortium:
// The purpose of a consortium is to declare a public memory space. The length is the same as that of the longest entry in the public data type,
When you assign values to the same consortium multiple times, it will overwrite:
# Include
Main ()
{
Struct date {int year, month, day;} today;
Union {long I; int k; char ii;} mix;
// The purpose of the consortium is to declare a public memory space.
// The length is the same as the longest entry in the common data type.
Printf ("date: % d \ n", sizeof (struct date ));
Printf ("mix: % d \ n", sizeof (mix ));
// The following value assignment, which is defined first will be overwritten.
Mix. I = 99;
Mix. k = 18;
Mix. ii = 'a ';
Printf ("I = % ld", mix. I );
System ("pause ");
}
15. enumeration:
# Include
Enum WeekDay
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};
Int main (void)
{
// Int day;
Enum WeekDay = Sunday;
Printf ("% d \ n", day );
System ("pause ");
}
16. typedef:
Declare custom data types, and use various original data types to simplify programming.
Typedef int haha; // declare an int Data Type
Example:
# Include
Typedef int haha;
Int main (void)
{
Haha I = 3;
Printf ("% d \ n", I );
System ("pause ");
Return 0;
}