C Language Learning

Posted by Jabop on Tue, 21 Sep 2021 08:35:36 +0200

C Language Learning


1. Some piecemeal points of knowledge:

Run environment VC++ 2010, remember to modify fonts and add commands "Run (but not debug)", display line numbers, etc.

You need to modify the main code file suffix to'.c'after creating the project

How does it work after writing the code?
C Required after writing code"Compile"generate.obj Files and some corresponding library files, then click"Connect",You can put obj Associate with library functions to generate an executable.exe

Shortcut Configuration: Tools > Options > Keyboard > Comments

2. Code formatting, one-click comments, etc.


1. Variables

We define a variable that actually uses part of the computer's memory and points to the data stored in that space.

The variable itself needs memory, so it has a pointer

2. Notes on printf

a. corresponding to int, double(float), char and other data types, corresponding to%d,%. XF (default reserve 6 digits after decimal point),%c or%s


In C, there are several data types according to the function of the data and the size of the memory occupied: basic type, construction type, pointer type and void type.

The amount of memory the data occupies depends on the computer's compiler, operating system, and number of digits in the system

Take windows as an example

win32						 Number of bytes
char,unsigned char 			  1
short,unshort				  2
int,unsigned				  4
long,unsigned long,long int   4 
float						   4
double,long double            8

win32Number of bytes
char,unsigned char1
long,unsigned long,long int4
double,long double8

2.1 Integer, floating point data types

Floating-point data can define characters or strings, note that escape characters are one character, such as:\n

2.2 boolean type boolean

There is no boolean defined in C89 standard, usually half true and half false through 0 and 1

We can define it through macros

#define TRUE 1

#define FALSE 0

The C99 standard defines macro definitions and needs to import <stdbool.h>

2.3 Data Type Conversion

If it is a mixed data operation, the limit is converted to the most accurate data type, and then the operation is performed

If it is a cast (high precision - low precision), truncate instead of rounding float a = (float)b

2.4 Getting started with pointers

In C, data is stored in the computer's memory space. Byte = 8 bitsAs the smallest storage unit of a computer, many bytes make up the computer's memory space. To distinguish between different memory spaces, we numbered these spaces, which are pointer values, also known as addresses. So each pointer has its own memory space, in which we store the data we need.

So to clarify a concept, no matter what type of data, as long as the computer needs to use it, it needs to occupy a certain amount of memory.

Then he has his own pointer.

Several operations on pointers are defined in C:

1. Pointer variables int *p, float *p, etc., which can store pointers

2. Take pointer: get a pointer to a variable through the'&'symbol

3. Solve Pointer: Get the value in the memory space that a pointer variable points to through the'*'symbol. That is, get the value that a pointer points to.

2.5 Value and Address Delivery

1. Our basic data type, structure and so on are all transfer of values - essentially, they copy the content to accept variables and do not change the value of input

2. Address delivery needs to be aware that since the address is passed, and the address is often related to its corresponding memory space, this operation can change the value of a variable.

2.6 Constant

Constant, not modifiable

There are two ways to define

#define xx xx  --#undefine xx
const type xx;
define and const Differences:
define Definition without type, no type checking, may cause boundary effects(truncation)
define Is a simple replacement, no mathematical combination(brackets) 

2.7 Operator

1. Arithmetic Operators

Self-Addition and Subtraction Operators: ++, -

It is important to note that when assigning values, ++ I adds itself first, and i++ adds itself after assignment.

If used independently, ++ I and i++ are equivalent

2. Relational Operators


The result of the operation is represented by true (1) and false (0)

And, or and not, respectively: &, |,!

&&: Short-circuit phenomenon (also called logical short-circuit)

3. Assignment Operators

+= ,-=, /=

Bitwise Operators

4. Ternary Operators

Expression 1? Expression 2: Expression 3

if 1 is true, Execution 2

else type 3

2.8 Operator Priority

Commas have the lowest priority and the rest of the viewable data

2.9 Variable Naming Specification

Constants are all capitalized, variables cannot start with numbers (combining letters, numbers, underscores), but be careful not to duplicate names with some keywords!


1. Program structure: Sequential structure, Select (Branch) structure, Loop structure

Branch structure: single-branch, multi-branch - through if and switch statements

Loop structure: through for and while statements

for loop - assign values first, execute a loop body once, make judgments, then execute the statement after the last colon

Note: The location of the memory space of the loop variable in the for loop is unchanged. The program only modifies the values in the memory space to meet the needs of the loop

while loop - Judge first, if true, execute the loop body.

do-while - execute once before making a judgement.

for and dowhile loops are judgements of execution first, except that the former knows the number of loops and the latter does not.

Can be nested

Note: There is also a go to statement, which requires defining labels. Generally in programs, to avoid confusion, it is not recommended to use

2. Enumeration

Enumeration is a construction data type of C

enum Day//Construct enumeration type, create enumeration element
};//Note that there is a semicolon here

enum Day day //Definition generates an enumeration variable whose value can be obtained by printing an enumeration element
    //You can synthesize a sentence above
enum Day

The benefit of enumeration is that when you have more custom data to use, you can reduce the amount of code you write and mention readability

For example: Our previous define Boolean type, assuming that this type is not only two elements (0 and 1), but more, you can consider enumeration.

3. Functions

Simple syntax for 3.1 functions:

Return type function name(Input parameters can be written if not void Or not write){
    Function Body...
        return xxx; //Return value
//If the function you want to build doesn't return a value, we can use void
void Return type function name(input parameter){
    Function Body...

(Functions open up a function stack each time they execute, and recursion is the same thing. Equivalent to every call to a function, a new function stack is opened, which is a form of memory storage for the program running in C. Program running is a kind of stack operation, the main main function is called the main stack, which stores the data needed for the program to run. When the function is executed, the stack starts fromDestroy by Move

~Value and Reference (Address, Pointer) Passes:

Reference passing is generally [array] and [pointer]

3.2 Header File References

Header file construction:

You need an.h file and a.c file with the same name.

The operation is to declare a function in the.h file and construct a specific function in the.c file.

Differences between #include< >, #include ""

The former applies libraries in the path of c's own library, while the latter refers to libraries in the relative path of.c files - in general, we use custom libraries in the latter way.

3.3 Variable Initialization

To avoid unnecessary memory usage and exceptions to variable references, we need to develop a good habit of initializing variables

Where integer and floating-point variables are initialized to 0 and 0.0

Initialize to NULL if it is a point er


1. Computer Memory Distribution

Computer memory can be divided into the following sections

Memory areafunction
Stack areaStoring local variables
Heap AreaStoring data dynamically allocated by malloc functions
Static ZoneStoring global variables and static data
Code areaStore code/instructions

2. static keywords

Static variables are initialized only once, and then the data is stored in the static area. The nature of the static area makes it similar to a global variable, which can be called and modified multiple times, rather than destroyed with the end of the function.

So the scope of a static variable is in the life cycle of the program file. It differs from other general global variables in that a general global variable can be referenced in another program through the exterm function, but a static variable cannot.


//To reference a function or variable in another file in another program file, use an extern declaration

Acting on global variables: effectively reducing coupling between modules

Act on local variables: Give global properties, extend the life cycle of a local variable, and preserve the values it points to.

We can treat the data declared by static as private, that is, only this program file can be referenced and no other program file can be referenced

3. Some commonly used functions

3.1 String Function


strlen()-Return string length

strcpy(* a,* b)-Coverage Copy b reach a

strcat(* a,* b)-String Connection

3.2 Date, Time Function


time_t curtime;time(&curtime)—Time Initialization

ctime(&curtime)-Returns a string representing the local time, including time and date

difftime(time1,time2)-Count the difference between two points in time

3.3 Common Mathematical Functions


pow(x,y)-Return x Square root
sqrt(x,y)-Return x Open y Power
fabs(x)-Return x Absolute value

4. Conversion of basic data types and string types

Character Array for String in C

4.1 Basic data types converted to strings

Sprintf (str,'%d', a) - results can be stored in strings

%8.2f: indicates a total of 8 digits + 2 digits after the decimal point, not enough space to fill

4.2 String to Basic Data Type


atoi(str) - Conversion function (integer)

atof(str) - Conversion function (decimal)

5. Preprocessing commands and macro definitions

5.1 Preprocessing: Simple operations on source files before compilation begins

Functions: for debugging and modifying programs, cross-platform use of code and program modularization

if __win32


elseif linux


5.2 Macro Definition: #define xx xx - A string definition that is essentially a simple replacement

#define UINT unsigned int
#undef XXX xxx

Both macro definitions and typedef s can redefine data types, except that the former is handled before compilation by the compiler and the latter by the compiler.

Macro definitions can also take parameters

#Define MAX(a, b) (a>b)? A:b - A formal parameter is passed in
//Note: MAX should not have spaces between parameters, which will make the program think the macro definition is parameterless
//In a macro definition, a parameter does not have to declare a data type because it does not need to be allocated memory, but it needs to have a clear data type when called

Differences between 5.3 functions and macro definitions with parameters:

Keep in mind that macro definitions are a simple replacement that can cause problems such as repeated references and modifications to some parameters

6. Arrays

Data type: Construction type

6.1 Define Array

int, char, double (data type)+[n]

sizeof() - Gets the total size of the array

int a[3];

a_Len = sizeof(a)/size(int);-Returns the length of an array

6.2 Arrays and Memory

The array name represents the first address of the array

/ The memory space of each element in the array is continuously distributed: address in hexadecimal, address + bytes, and so on

6.3 Considerations for using arrays

//Notice that the array name represents the address of the first element of the array, so when we pass the array name in a function, we are actually passing the address of the first element of the array. For this reason, the operation on the array in a function is referential passing, and some of the corresponding operations modify the values in the array elements.
//array[n] - A value stored in the memory space corresponding to the address of an element in the reference array

7. Character Array and String

C uses character arrays to store strings, which are denoted by''. Note that single quotation marks can extract ASCII codes, which are integer variables

So character arrays and strings end with "\0"

char ary1[] = {'a','b','c'};//No end flag'\0'was specified, which can cause garbage
char ary2[3] = {'a','b','c'};//No end flag'\0'was specified, which can cause garbage
char ary4[] = {'a','b','c','\0'};
char *ary3 = "abc";


//Some Difficulties
char str[10];
//str = "Hello!"; //This error occurs because: str is a character array name, which itself represents the address of the first element of the string, is a constant and cannot be modified. Similar to 1 here in int i=1
//Hello is actually an array and represents a list of memory spaces (addresses), so we can do this by assigning pointer variables


Mouse Click to set breakpoint

F5 Starts debugging, jumps to the next breakpoint

F10 Step by Step

F11 Statement by Statement (Entering Function Body) shift+F11 executes quickly and jumps out of the function


1. Pointer (piont)

C Language Essence

Number representing memory space

//Pointer Definition:
int *p;
char *p;
//Pointer operation
 Pointer addition or subtraction refers to byte operations,Because the pointer is 16-digit,One byte is 8 bits(2^8)
++,--//In this case, auto-addition and auto-subtraction refer to unit operations, i.e., int-type pointer++ equals the pointer plus a byte of int (4 bytes)
*Solver pointer,&Pointer character
//The array name itself is a pointer to the first element of the array, and the pointers to the elements within the array are continuously distributed (in units of their own element size)

2. Pointer Array

int *p[3];
As the name implies, every element in an array of pointers is a pointer variable.

3. Multiple pointers (pointer dolls)

As mentioned earlier, both pointer variables and other variables need to occupy a certain amount of memory of the computer. They all have their own memory number (pointer), so there are multiple pointers to represent the memory number of pointer variables.

int **p;
int ***p;
It works like a pointer, except for multiple pointers, which unlock the pointer*Return still pointer value

4. Pointer function

int Function name(Parameter 1, parameter 2)		//Define normal functions
int *Function name(Parameter 1, parameter 2)		//Define Pointer Function

Role: Can return pointer (address).

Note: Local variable addresses in pointer functions cannot be returned because of the nature of the function stack. If this is required, we can store a local variable in a static zone by defining it as a static variable and not destroy it with the end of the function. This allows us to return the address of a local variable.

Local data is destroyed not because they have been cleared, but because the program has given up access to this memory, which can be used by subsequent code. So sometimes, if two pieces of code use the same memory, unexpected results may occur.

5. Function Pointer

Need to specify the return pointer type beforehand, otherwise return by default void Type pointer, which does not point to data such as variables, functions, etc. (nothing)
int (*Pointer Name)(Parameter 1, parameter 2);	//Reference
int (*Pointer Name)(void);  			//No reference

Functions, like data such as variables, also require memory. Function pointers can return the first address of the function stack in the code area, and we can reference functions in this way.

//Usage method
(*Pointer Name)(Parameter 1, parameter 2)

6. Callback Functions

Other functions are called within a function, which is called a callback function. This can be done by calling a function pointer.

void initArray(int  *array,int arraySize,int(*f)(void))
{Function Body ...
//Here int(*f)(void) indicates that you need to pass in a parameter to the function pointer, which is how the callback function is implemented
//So we can define the callback function we need, passing its pointer into another function

7. Dynamic memory allocation

For some temporary data, we can set up dynamic memory allocation zones, reasonably size them in an area called a heap, and even release them when they are not needed

Note: Data stored in the space requested in the heap can only be referenced by a pointer because it is not declared intentionally externally with other variables

7.1 Dynamic Memory Allocation Related Functions

1,malloc(Memory size (bytes))			//Allocate a space of the desired size
2,calloc(n,Memory size (bytes))			//Allocate n contiguous spaces of desired size for array storage
3,free()							 //Release memory
4,realloc(void *p,Memory size (bytes))  //Adjust Allocated Size Space

void *p - A pure address where you can get some data, called an untyped pointer variable, but it doesn't feel useful or point to the value stored in the address

8. Structures and Commons

struct Cat{
    Define the required data type(member)
    char *p;
    int i;
}					//Declarations similar to class properties in python
//Write 1:
struct Cat cat1;
struct Cat cat2;    //Declare struct variables, similar to instantiation of classes

//Writing 2:
struct Cat cat1,cat2;

//Writing 3:
struct Cat{
    Define the required data type
    char *p;
    int i;

//Write 4 (not recommended, this only applies when the required structure variables are limited):
struct {
    Define the required data type
    char *p;
    int i;

// ******************************** //
cat1.p = xxx;
cat1.i = xxx;

Some habits: Just like macro definitions are all capitalized, structs are typically constructed in initial capitals

Example: PDF 321 page case

8. Commons (Commonwealth, Union)

Each member (property) of the 8.1 structure consumes different memory and has no effect on each other.

Sharers interact, with the advantage of reducing memory usage

union data{
    int n;
    char ch;
    double f;
union data a,b,c;
// It works like a structure!!

//Can be used in conjunction with structures to reduce memory usage
struct Cat{
    Define the required data type(member)
    char *p;
    int i;
    union data{
    int n;
    char ch;
    double f;

8.2 Common Memory Layout

All members of a common body share memory space, which is based on the data type that occupies the most memory

Memory is continuously distributed in bytes from low to high. Each byte (the smallest memory unit) stores different values. Each member references data in different bytes based on the size of memory they occupy, so their data interacts with each other.

​ (Aweo 2021.09.21)

  • //
    cat1.p = xxx;
    cat1.i = xxx;
**Some habits: Just like macro definitions are all capitalized, structs are typically constructed in initial capitals**

Example: PDF 321 Page Case

### 8. Commons (Commonwealth, Union)

8.1 Each member of a structure(attribute)Occupy different memory and have no effect on each other

Shared entities interact,The advantage is that it can be reduced**Memory occupancy**

union data{
    int n;
    char ch;
    double f;
union data a,b,c;
// It works like a structure!!

//Can be used in conjunction with structures to reduce memory usage
struct Cat{
    Define the required data type(member)
    char *p;
    int i;
    union data{
    int n;
    char ch;
    double f;

8.2 Common Memory Layout

All members of a common body share memory space, which is based on the data type that occupies the most memory

Memory is continuously distributed in bytes from low to high. Each byte (the smallest memory unit) stores different values. Each member references data in different bytes based on the size of memory they occupy, so their data interacts with each other.

​ (Aweo 2021.09.21)

Topics: C