C Language Basics

// Import header files. It contains the important printf.
#include <stdio.h>

// the entry function.
// Parameter 1 indicates the number of parameters entered. Parameter 2 stores all parameters.
// The return value is int, where 0 indicates success and negative values indicate failure.
int main(int argc,char* argv[]){
    printf("Hello World! \n");
    return 0;  // Indicates that the command is successfully executed.
}
Copy the code

By compiling and executing instructions:

Clang is used for compilation on MAC and GCC is used for compilation on Linux.

gcc/clang -g -o Hello xxx.c

  • -g indicates the debug mode, which contains debugging information.

  • -o Specifies the name of the output file

  • XXX. C source code

Do this on MAC or Linux using./Hello

Integration of the running environment, the background is actually this step.

Common base types

  • Short, int, long

  • Float (Single-precision floating-point type, generally float is used.) , double (high precision floating point type, suitable for scientific calculation, etc.)

  • Char * (string)

  • Void (when you don’t care about the type)

Basic operation

  • +, –
  • *, /, %
int main(int argc,char* argv[]){ 
    int a = 10;
    float b = 12.5;
    // Print the result; A +b=22.500000 (float type)
    printf("a+b=%f\n",a+b);
    // Print the result; . , a*b=125.000000 (float type)
    printf("a+b=%f\n,a*b=%f\n",a+b,a*b);
    
    char c = 'a';
    // Print the result; (c+1=b, c+2=c,...)
    printf("c=%c\n",c+5);
    // Print the result; C =102 (the actual code of f is 102)
    printf("c=%d\n",c+5);
    
    int d = 10;
    int e = d % 6; / / to take over
    int f = d / 6; / / to take
    // Print the result; e=4,f=1
    printf("e=%d\n,f=%d\n",e,f);
    
    return 0;  // Indicates that the command is successfully executed.
}
Copy the code

Variables and Constants

  • int a = 0; // The variable can be reassigned. You don’t have to assign an initial value.

    The physical meaning of a variable in a computer is a register. Registers store data temporarily and are very fast. When a piece of data is fetched from memory, it is first stored in a register. When this value is changed, the register is refreshed and erased. This will speed up the execution of the program.

  • const int len = 265; // Constant, immutable. You need to assign an initial value.

    When compiling a program, a static buffer is set up in the program. The static buffer is protected and cannot be modified in the normal way. But if you know the physical location of the memory, you can change it.

An array of

An array is an ordered sequence of elements (C arrays store elements of the same type, and the index starts at 0). To define an array in C, you need to tell the compiler how long the array is. C language array definition; char c[2], int arr[10]

int main(int argc,char* argv[]){ 
// int arr[10];
// arr[0] = 1;
// arr[1] = 2;
// printf("%d,%d\n",arr[0],arr[1]);
    
    int arr[10] = {1.2.3};// Print the result; 1,2,3,0 (by default, arrays are initialized to 0 without assignment.)
    printf("%d,%d,%d,%d\n",arr[0],arr[1],arr[2],arr[3]);
    
    float f[2] = {1.2};
    // Print the result; 1.000000, 2.000000
    printf("%f,%f\n",f[0],f[1]);
    
    return 0;
}
Copy the code

The structure of the body

// It has no concept of protection (e.g. Private, etc.)
struct st {
    int a; Members / / a
    int b; B / / members
};
Copy the code
// Struct can be understood as a class
struct st{
    int a;
    float f;
};

int main(int argc,char* argv[]){
    struct st ss;
    ss.a = 12;
    ss.f = 10.2;
    // Print the result; Struct: 12, 10.200000
    printf("struct:%d, %f\n",ss.a,ss.f);
    
    return 0;  // Indicates that the command is successfully executed.
}

Copy the code

Enumerated type

Enumeration can be thought of as a restricted integer. Generally, it is used in a certain range of values. For example, the value of an attribute can only be 1, 2, or 3.

enum em {
    red_color = 0.// The value is 0 if the value is 1
    green_color,    If the value is 1, the value is 2
    black_color     // If the value is 2, the value is 3
};
Copy the code
enum em {
    red_color = 5,
    green_color,
    black_color = 10,
    yellow_color
};

int main(int argc,char* argv[]){
    enum em ee;
    
    ee = green_color;
    // Print the result; enum:6
    printf("enum:%d\n",ee);
    
    ee = yellow_color;
    // Print the result; enum:11
    printf("enum:%d\n",ee);
    
    return 0;  // Indicates that the command is successfully executed.
}
Copy the code

Pointer to the

Pointers are variables that hold memory addresses. The value stored in the address space, in C language, in addition to ordinary values, it can also store another memory address, this value is a pointer, through this value can access other addresses, and then you can take out the address stored in the data. So, this value can have multiple meanings, depending on the business logic.

Pointer functions:

  • Improve execution efficiency.

    Normally, a string is passed into a function. When a function operates on the string, it is a copying process. The function copies the string into its own function space and stores it. Multiple copies can be a huge waste of the entire CPU. A pointer, on the other hand, just passes the address of the string to the function, and the function accesses the string through the pointer.

  • More control.

    Because it has the ability to access addresses. For example, the hardware of a computer actually has a corresponding mapping address to the operating system layer. Through this address, THE C language can access the hardware device and control it. C is a lower-level language that can access devices.

Pointer operations:

  • One is the operation on the pointer itself.

    It’s actually an operation on the address. For example, when you get a pointer to a certain space, you can add, subtract, multiply and divide the pointer. If you add one to the pointer, it points to the next space.

  • The other is to operate on the content pointed to.

    When a pointer points to a memory address, it can obtain its contents and add, subtract, multiply and divide the contents.

Pointer definition and use:

Type * var:

  • Type refers to a type, such as int, void, etc.
  • And * means that the variable is a pointer, so you can write it close to type, which is a pointer to that type, and you care what type the pointer is, or you can write it close to var, which means that the variable is a pointer and you don’t care what type it is. There is no difference between the two for the compiler, but it is best to use the same style when writing code.

*var: gets what the pointer points to

Heap memory allocation and release:

Void * mem = malloc(size);

Free memory: free(mem);

#include <stdio.h>
#include <stdlib.h> // the header required by malloc()

int main(int argc,char* argv[]){
    // malloc() normally returns void*.
    // malloc() is in the 
      
        header.
      
    char* p = (char*)malloc(10); // Allocate a space of ten characters
    *p = 'a';      // Position of the first character
    *(p+1) = 'b';  // The position of the second character
    // Tell printf the memory allocation address,
    // printf prints the contents of the space pointed to by the p address as a string.
    printf("%s\n",p); // Print the result; ab
    
    // Free the space pointed to by p
    // System management returns memory to heap space
    free(p);
    *p = 'd';
    // Even if you free the space, you still know the position of the space, so you know where p is pointing.
    // Even if it is released, it can still be operated on.
    printf("%s\n",p); // Print the result; db
    
    // To prevent access to this address, point to NULL and set it to invalid.
    p = NULL;
// *p = 'e'; // crash
    
    return 0;
}
Copy the code

Common memory space

Stack space: Stack mechanism, last in first out. The biggest feature is that functions written in C language, all variables allocated within the function are allocated in the stack space, when exiting from the function, resources allocated from the stack space are automatically released. (Allocated resources are limited; the default stack size is 8 MB.)

Heap space: The malloc() function is explicitly used to allocate resources. When memory is used, the free() function is used to free resources back into the heap space so that resources can be allocated from the heap space while others are using it. (The allocated resources can be considered almost unlimited, suitable for times when large space is needed.)

Memory mapping: Some dynamic libraries import it directly into the memory mapping area, which is also a dedicated space. For example, if a file is mapped to the memory, the content of the file is mapped to the memory. When the value in the memory is changed, the file is automatically updated in the system.

Partition of Linux memory address: 4G 32-bit system

0 to 0x08048000: This is the protected space and our process cannot access it.

Code: Stores the code segment to be executed by the process.

Heap space is growing from the bottom up, stack space is growing from the top down, and each allocation is going down. The division of heap space and stack space is to reduce collisions.

Shared libraries, or memory-mapped areas, map files into mmap space when you want to change files in memory.

Memory leak:

  • Constantly requesting memory for the system.
  • The requested memory is not used and is not released.

Wild pointer: Occupying someone else’s memory is called a wild pointer.

Conditional judgment and loop

Comparison operations: >, <, >=, <=, ==,! =

If/else statements:

if( a> b){ ​ … }else{ ​ … }

For statement:

for(int i =0; i<100; i++){ ​ … }

While statement:

#include <stdio.h>
#include <unistd.h>   // usleep() requires a header file

int main(int argc,char* argv[]){
    while (1) {  / / death cycle
        printf("while... \n"); // Prints once a second
        usleep(1000000); / / ms
    }
    return 0;
}
Copy the code

function

In C language, naming is usually in the style of Linux. Words are connected by underscores, and words are usually abbreviated.

// void Return type
// func function name
// int a parameter
void func(int a){...// The function should not be too large, usually no more than 50 lines.
}
Copy the code

Function pointer: A pointer variable to a function. C language function pointer can be realized in C++ polymorphism, that is, the function pointer can be defined to point to a function, can also point to b function, external layer, only need to call this function pointer. (Polymorphism is when a function can have different meanings)

Function pointer format: return value type (* pointer variable name) ([parameter list]);

int func(int x);  // Declare a function
int (*f)(int x);  // Declare a function pointer. The return type and parameter must be the same as the specified function.
f = func;  // Assign the first address of the func function to the pointer f. And then you just call f.
Copy the code
#include <stdio.h>

int func(int a){
    printf("a=%d\n",a);
    return 0;
}

int func1(int b){
    printf("b=%d\n",b+5);
    return 0;
}

int main(int argc,char* argv[]){
    int (*f)(int);
    // in C++ this is called polymorphism.
    // At the upper level, the function pointer f is called, but at the lower level, different results are returned.
    f=func;
    f(2);
    f=func1;
    f(3);
    // Print the result; a=2 b=8
    return 0;
}
Copy the code

File operations

FILE type: FILE* FILE; (FILE* is called a pointer under Linux and a handle under Windows.)

Open FILE: FILE* fopen(path,mode);

Close a FILE: fclose(FILE*);

#include <stdio.h>

void createfile(char* filename){
    // open/create file
    FILE* file = fopen(filename,"w");
    if(! file) {printf("Failed to create file (%s)\n",filename);
        return;
    }
    
    // Write to the created file.
    // Parameter 1 refers to the written string, parameter 2 refers to the size of each item in the string, parameter 3 refers to the number of items, parameter 4 refers to the file to be written to
    size_t len = fwrite("aaaaa".1.5, file);
    if(len ! =5) {
        // size_t prints %zu.
        printf("Failed to write file,(%zu)",len);
        fclose(file);
        return;
    }
    
    printf("Successed to write file\n");
    fclose(file);
    printf("Successed to create file\n");
}

void read_data(char* filename){
    FILE* file = fopen(filename,"r");
    if(! file) {printf("Failed to create file (%s)\n",filename);
        return;
    }
    // define 1k size and initialize to 0.
    char buffer[1024] = {0};// Parameters: where to store the read data, length, how much to read, and from where to read.
    size_t len = fread(buffer, 1.10, file);
    if (len <= 0) {
        printf("Failed to read file! \n");
        fclose(file);
        return;
    }
    printf("read_data:%s\n",buffer);
    fclose(file);
    return;
}


int main(int argc,char* argv[]){
    // create file
// createfile("/Users/jianghouren/Downloads/1.txt");
    // read file
    read_data("/Users/jianghouren/Downloads/1.txt");
    return 0;
}
Copy the code

note

References:

Moocs – Audio and Video Basics (Li Chao)

Welcome to follow wechat official account:No reason also