Like attention, no more lost, your support means a lot to me!

🔥 Hi, I’m Chouchou. GitHub · Android-Notebook has been included in this article. Welcome to grow up with Chouchou Peng. (Contact information at GitHub)

Today in history

On March 19, 2019, a new record was set for calculating PI \ PI. Google announced that haru Iwao, a female programmer from Japan, had broken the world record for the number of digits of PI \ PI PI with the help of the company’s cloud computing, accurate to 31.4 trillion decimal places. The program reportedly ran on 25 virtual machines for 121 days and involved 170 terabytes of data. — The Great Programmer

The data type

In C language, data types are divided into signed and unsigned. The default is signed.

type A synonym for The storage space
signed char There is no 1 byte
int Signed int, signed 2 or 4 bytes
short Signed short, short int, signed short int 2 –
long Signed long, long int, signed long int 4 bytes
long long (C99) Signed long long, long long int, signed long long int 8 bytes
type A synonym for The storage space
unsigned char There is no 1 byte
unsigned int unsigned 2 or 4 bytes
unsigned short unsigned short int 2 –
unsigned long unsigned long int 4 bytes
unsigned long long (C99) unsigned long long int 8 bytes

C defines the length of an int as no shorter than short and no longer than long. The length depends on the target platform specified at compile time.

The macro

Macro is a mapping of “name-replacement text”, which expands the place where the macro name appears in the source code to the specified replacement text when preprocessing.

Double data[ARRAY_SIZE]Copy the code

Macros with arguments Note that there must be no Spaces between the macro name and the open parenthesis, otherwise it will become a macro with no arguments.

#define DISTANCE(x, y) ((x)>=(y) ? (x)-(y) : (y)-(x))
int d = DISTANCE(1,2
Copy the code

variable

Variable types scope The life cycle Memory area
A local variable Function of the internal function The stack area
The global variable The whole project process Data area
Static local variable Function of the internal process Data area
Static global variable Inside the source file process Data area

function

Function types scope Storage location
Global function The whole project Code section
Static functions Inside the source file Code section
  • Function declarations must precede function calls. Function declarations can omit parameter declarations, depending on the fact that C does not have function overloading (C++ does). A function definition does not have to come before a function call. Parameters can take no parameter names.
  • Printf placeholder
A placeholder meaning
% d, % I Signed integer
%u An unsigned integer with the highest bit as part of the value
%o Signed integer (octal)
%x Signed integer (octal)
%X Signed integer (hexadecimal), the letter is displayed in uppercase
%c character
%s string
  • Inline function: The function body is directly embedded in the position of the function call at compile time. The function call instruction is no longer executed at runtime, saving the overhead of the function call. Inlining comes at the cost of code bloat, because each inlined function is called with a copy of the code. As the total amount of code increases, the program will occupy more memory space. Therefore, inlined functions are only suitable for short functions, and inlined functions cannot be called recursively.
inline void fun(); / / null void fun () {} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - void fun (); Inline void fun() {// valid}Copy the code

Note: Inline is valid only if it is applied to the function definition, which is not.

keywords

The static keyword is used

  • Static storage type: Modifies a variable to be a static local variable or a static global variable.
  • Static function: Used to modify a function to be static.

The role of the const keyword

  • Modifier variable/parameter: The value of a variable cannot be modified
const int a = 1; a = 2; (X) // Cannot assign to variable 'a' with const-qualified type 'const int' note: const and int can be interchangeable. const int a = 1; int const a = 1;Copy the code
  • Modifier pointer:Const can be used with pointer variables as follows:
    • 1. Close to a const modifies the pointer variable itself. The pointer is immutable.
    • 2, Const far from the name of a variable modifies the variable to which the pointer points.
const int * p; // int const * p; Int * const p; // pointer to immutable const int * const p; Const * const p; Int a = 1; const int * p = &a; *p = 2; (X) // Read-only Variable is not assignableCopy the code
  • Modifier function return value: normally used to return a pointer function, indicating that the data to which the return pointer points is not allowed to be modified
const * int func(); // const is far from the name of the variable, as in the case of const int * p mentioned above.Copy the code

Const versus define

Const and define are similar in that they both define a value that is not allowed to be changed. They are both “constants” for functional purposes only. But from an implementation perspective, they are not constants.

  • Define is a precompilation instruction. The macro defined by DEFINE is expanded into the specified text in the preprocessing stage, and the macro defined by DEFINE is not present after compilation.
  • Const is a variable modifier. It is essentially a read-only variable.

The function of the extern keyword

  • Modifier variable or function: Indicates that the variable or function is a global variable or function defined in an external file, prompting the compiler to look it up in the external file.

main.c

// If you do not use extern, the variable cannot be found. extern int g ; g = 1; extern int g = 1; // Extern = extern; // extern = externCopy the code

other.c

int g;
Copy the code
  • Extern “C” : Implementation C++ code calls C code that compiles links the way C does.
// if in C++, #endif // all of your legacy C code here #ifdef __cplusplus} #endifCopy the code

The role of the volatile keyword

Modifies a variable to remind the compiler that it can change at any time, and that every time a program needs to read the value of a variable, it needs to read it directly from the address of the variable instead of using the cache in the register.

volatile int a;
Copy the code

The role of the include keyword

#include < system resources >Copy the code

An array of

string

  • A string is essentially a\ 0The C-style string is automatically appended to the end of the array\ 0Terminator.
char *p = "xurui"; p[2] = '1'; Cannot modify the global region printf("%s", p);Copy the code
  • Traversal string
char *str = "xurui";
while (*str) {
    ...
    str++
}
Copy the code
  • String conversion

Atoi: Converts a string to a long integer

Int atoi(const char * STR) #include <stdlib.h> int result = atoi("1"); Similar functions: atol, ATof, strtodCopy the code

How to judge the conversion success?

  • String comparison

STRCMP: compares two strings STRNCMP: compares two strings at most the first n characters

Function prototype: Int STRCMP (const char *str1, const char *str2) int STRNCMP (const char *str1, const char *str2) Size_t n) returns the following values: - If the return value is less than 0, str1 is less than str2. - If the return value is greater than 0, str1 is greater than str2. - If the return value is 0, str1 equals str2. #include <string.h> int result = STRCMP ("1", "2")Copy the code
  • Characters locate

STRSTR: Finds the location of the first occurrence

Char * STRSTR (const char *haystack, const char *needle); char *text = "peng xurui"; char *subtext = "x"; char *pop = strstr(text, subtext); printf("%s\n", pop); // output xurui int index = pop-text; Printf (" index: %d", index); / / output 5Copy the code
  • String splicing

Strcat: Concatenates two strings

Char *strcat(char *dest, const char * SRC);Copy the code
  • Case conversion

Tolower: converts to lowercase characters toupper: converts to uppercase characters

Int tolower(int c); Char c = 'A'; tolower(c);Copy the code
Int toupper(int c); Char c = 'a'; tolower(c);Copy the code

Pointer to the

  • & fetch the address, * fetch the value in the address, %p placeholder for the address.
  • Pointers hold memory addresses, but Pointers also have memory addresses themselves.
  • The size of a pointer has nothing to do with the type of variable stored at the address it points to, but only with the word length of the operating system. The sizeof(int*) pointer is 4 bytes on 32-bit systems and 8 bytes on 64-bit systems.
  • Wild Pointers are Pointers to memory addresses that are not available, such as addresses that are outside the range of an array. Wild Pointers are not null Pointers.
  • A function pointer is a pointer to a function. The address of a function is the first address of the function’s storage space. Function Pointers are defined as: function return value type (* pointer variable name) (function argument list);
int Func(int x); Declare a function int (*p) (int x); Define a function pointer p = Func; Assign the starting address of the Func function to the pointer variable p (*p)(9); Call function (p)(9); You can omit *. This is a function pointer special caseCopy the code
  • Row pointer
  • Column a pointer

Heap memory management

  • Malloc: Allocate a new contiguous space on the heap
Void *malloc(sizt_t size); #include <stdlib.h> int *p = (int *) malloc(sizeof int); if (! P) {printf(" application failed "); }Copy the code
  • Calloc:Allocate a new contiguous space on the heap and initialize to0
Void * calloc(size_t num_elements,size_t element_size) void* calloc(size_t num_elements,size_t element_size); #include <stdlib.h> int *p = (int *) calloc(5, sizeof(int)); if (! P) {printf(" application failed "); }Copy the code
  • Realloc: Adjusting a block of allocated memory space (expanding or shrinking)
Realloc (void * PTR, size_t new_size); realloc(void * PTR, size_t new_size); #include <stdlib.h> int *p = (int *) malloc(20 * sizeof(int)); int *p1 = (int *) realloc(p, 21 * sizeof(int)); int *p2 = (int *) realloc(p, 2000 * sizeof(int)); printf("%x\n", p); Ce4054c0 printf("%x\n", p1); Ce4054c0 printf("%x\n", p2); // output CE809800Copy the code

Realloc () returns a pointer to realloc(); realloc() returns a pointer to realloc(); 2) Otherwise, create a new memory block in the heap, release the original memory block, and return the address of the new memory block; 2) Otherwise, NULL is returned for allocation failure.

  • Free: Releases dynamically allocated memory blocks
The argument is free(void* pointer); #include <stdlib.h> if (p) {free(*p); p = NULL; // prevent dangling pointer from being stored}Copy the code

1) The memory allocated by malloc, calloc, realloc must be freed by free; 2) Do not release the same memory block repeatedly, because the operating system may allocate the space to other uses.

The structure of the body

  • Declarative structure
struct Student { char *name; int age; char sex; }; // A semicolon must be addedCopy the code
  • Initialize the structure
Struct Student mark; mark.name = "mark"; mark.age = 10; mark.sex = '1'; Struct Student mark = {"mark", 10, '1'};Copy the code

Note: Member variables in a structure are initialized to system values, unlike Java, which initializes member variables to zero values.

  • Class when declared
struct Student {
    char name[10];
    int age;
    char sex;
} mark = {"mark", 10, '1'},
tom, amy;
Copy the code
  • Structure nesting
Struct Student {char name[10]; int age; char sex; struct Sport { char *name; } sport; }; Struct Student mark = {"mark", 10, '1'}; struct Student mark = {"mark", 10, '1'}; struct Student tom = {"tom", 1, '1'}; mark.sport.name = "basketball"; tom.sport.name = "football"; printf("%s\n", mark.sport.name); // basketball printf("%s\n", tom.sport.name); // footballCopy the code

Note: The nested SPORT structure is two separate structures, two separate pieces of memory.

  • Structure pointer

A structure pointer is a pointer to a structure.

struct Student *p = &mark;
printf("%s\n", p->name); // mark
Copy the code

Where -> is the first-level member variable of the calling pointer.

  • The static and dynamic opening up of the structure
Stack struct Student mark; mark.name = "mark"; Struct Student *markP = malloc(sizeof(struct Student)); markP->name = "mark"; printf("%s\n", markP->name); // markCopy the code
  • Struct array

A struct array is an array whose elements are structs.

Static set up: the stack struct Student Student [3] = {{10, "mark", '1'}, {" Tom ", 1, '1'}, {},}; struct Student *p = &student; printf("%s\n", student[0].name); // mark printf("%s\n", (p + 1)->name); Struct Student *p = malloc(sizeof(struct Student) * 3); p->name = "mark"; (p + 1)->name = "tom"; printf("%s\n", p->name); // mark printf("%s\n", (p + 1)->name); // tom free(p);Copy the code
  • Structure alias
Typedef struct Student Student_; typedef struct Student * pStudent; Use aliases: Student *p = malloc(sizeof(Student) * 3); pStudent p = malloc(sizeof(Student) * 3);Copy the code

Note the differences between Clion and VS editors:

Struct Student *p = malloc(sizeof(struct Student) * 3); free(p); Student *p = malloc(sizeof(Student) * 3); free(p);Copy the code

To avoid inconsistency of source code between different compilers, we can define the same alias:

Define an identical alias typedef struct Student Student; Use aliases: Student *p = malloc(sizeof(Student) * 3);Copy the code

Tip: You can see in the source code that many structures have aliases defined just to keep the code uniform. C enumerations have similar problems.

  • Anonymous structure
Struct {// char *name; }; Struct {// char *name; } a1, a2, a3;Copy the code

File operations

  • Fopen: opens a file
Const char *filename, const char *mode) : 1) r: read 2) w: write 3) a: FILE * FILE = fopen(" FILE name ", "r"); if (! File) {// failed to open file} char buffer[10]; while (fgets(buffer, 10, file) { printf("%s", buffer); }Copy the code
  • Fputs: writes files
Int fputs(const char * STR, FILE *stream) uses FILE * FILE = fopen(" filename ", ""); if (! File) {// failed to open the file} fputs("xurui", file); fclose(file);Copy the code
  • EOF: End of File

Memory area

  • From low address to high address, the order is: code area, data area, heap area and stack area.
  • Code area: The binary code of the executable
  • Data area:
    • Data segment: static and global variables that have been initialized
    • BSS segment: uninitialized static and global variables
    • Rodata segment: constant values (such as string constants)
  • Stack area: Stores the stack frame corresponding to the function call
  • Heap area: dynamically allocated memory

— Picture quoted from Internet


Creation is not easy, your “three lian” is chouchou’s biggest motivation, we will see you next time!