Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Depth understanding of C language     - Linux server security - the web server configuration (Linux)

- crontab task scheduling Health Check (Linux)

- How to manage Vim plugin (Linux)

- To protect the temporary files for Linux security (Linux)

- Ubuntu install the camera driver (Linux)

- Thinking in Java study notes - Access modifiers (Programming)

- OpenStack image production in the CentOS 6.2 (Linux)

- CUDA (including GPU card driver) installation process under Ubuntu (Linux)

- How to Install Suricata IDS on a Linux system (Server)

- Sorting algorithm of dichotomy (binary) insertion sort algorithm (Programming)

- crontab cause CPU exception Analysis and Processing (Linux)

- Linux System Getting Started Tutorial: Linux file permissions brief description (Linux)

- Python objects (Programming)

- Python 3.5 will support Async / Await Asynchronous Programming (Programming)

- CentOS iptables firewall configuration (Linux)

- EChart simple and practical control on chart (Programming)

- Firewall chapter of Linux server security configuration (Linux)

- Ubuntu 14.04 after the restart the default maximum screen brightness solutions (Linux)

- Django template inheritance child (Programming)

- How to install and configure in Ubuntu 14.10 'Weather Information Indicator' (Linux)

 
         
  Depth understanding of C language
     
  Add Date : 2018-11-21      
         
         
         
  Language is just a tool, are any similarities between languages, a General Belden, the key is to understand the thinking behind the language, understand their thoughts, in any language, and make use on the line. Language no good or bad, since there is a natural in any language has its own value.

In an era full of OOP, why process-oriented C language can still be so active? This is mainly due to the language features of the C language itself. C language small and flexible, but also a pointer to deal directly with the hardware exists, so it is the only high-level language embedded development; because of his compact and flexible, we can use it to develop a range of gadgets, Unix / Linux from these gadgets is composed of an operating system; while using C language to develop high-performance applications.

1, the data type. C is a process-oriented language, but it can still achieve most object-oriented can be done. Such as object-oriented three characteristics: encapsulation, inheritance, polymorphism.

Package: C has a complex data structure called a struct. struct C is inside the structure.

If we want to encapsulate person, person may include name, gender, age, height, weight and other information. We can package it as follows:

struct Person {
    char name [20]; // Name
    char gender; // Sex
    int age; // Age
    int height; // Height
    int weight; // weight
};

When we did want to create a new object like OOP, we can:

struct Person p;

We can p direct assignment:

p.name = "whc";
p.gender = 'b'; // 'b' = boy; 'g' = girl
p.age = 25;
p.height = 175;
p.weight = 65;

Inheritance: Again use struct, we have to create a student body, while inheriting the structure Person, as follows:

struct Student {
    struct Person p;
    char number [20]; // Student ID
    int score; // Results
};

Student objects to be created and assigned:

struct Student s;
s.p.name = "whc";
s.p.gender = 'b';
s.p.age = 25;
s.p.height = 175;
s.p.weight = 65;
s.number = "20150618";
s.score = 90;

Polymorphism: C polymorphism in the implementation can be achieved by means of a function pointer. For simplicity, we assume that the Person of the structure, only a function pointer.

struct Person {
    void (* print) (void * p);
};

struct Student {
    struct Person p;
};

The print function Person and Student these two structures is implemented as follows:

void printPerson (void * person) {
    if (NULL == person)
        return;
    struct Person * p = (struct Person *) person;
    printf ( "run in the person !! \ n");
}
void printStudent (void * person) {
    if (NULL == person)
        return;
    struct Person * p = (struct Person *) person;
    printf ( "run in the student !! \ n");
}

We write a function to call them:

void print (void * person) {
    if (NULL == person)
        return;
    struct Person * p = (struct Person *) person;
    p-> print (person);
}
int main () {
    struct Person person;
    struct Student student;
    person.print = printPerson;
    student.p.print = printStudent;

    print (& person); // argument for the Person object
    print (& student); // argument for the Student object

    return 0;
}

In fact, this is not difficult to understand, either Person or Student, they have only one variable in memory, is that the function pointer, represents any type of void * pointers, when we cast it to type struct Person * When, p- > Nature is the incoming argument print the address pointed to print.

2, pointers and memory management

Whether asking which one works lion C: C language is the most error-prone places where? Basically, we'll get the same answer, that is pointers and memory overflow. So what is a pointer, the pointer is actually an address, the address may be the address of a variable, it can be the address of a function, whatever it is, anyway, a memory address.

For example, a variable a, we define a variable that holds a pointer to the address:

int a = 0;
int * p = & a;

If it is a function? We define a function, and then use a function pointer to save the address of the function:

int min (int a, int b) {
  return a < b a: b;?
}

int (* f) (int, int);
f = min;

Sometimes we may think, do we must first define a variable or function, then its address pointer to it? You can not directly use the pointer, or directly assign a constant pointer to it? First, we do not know what is available in memory address, which is not available, whenever we define a pointer that points to an undefined memory, this is the legendary wild pointer. If we give this pointer points to the memory assignments, it is possible to cover some very important data, so whenever we define a pointer, it is best to give it assigns a default address or NULL; if we assign to a pointer constant, the same reason.

Pointer type to be consistent with the type of the variable (if we did not mean to them inconsistent), the so-called types, only variables have been manifestations, in fact, in memory, they are nothing but 0101 binary, when we use 32bits original code is represented it is unsigned; when we 32bits complement representation when is signed; when using floating-point representation when that float; when a more complicated custom is said in struct; with the union can well understand that.

Now we are speaking about memory, here we only discuss the user memory area:

Generally divided into five areas:

(1) the program code area: a place to store code instructions

(2) global (static) variable area include: initialization, uninitialized global and static variables

(3) Character constants District: Store string constants in the C language, this is very easy with an array of characters defined in the stack confused, when we define as follows:

int main () {
  char * str0 = "Hello World!"; // character constant region
  char str1 [] = "Hello World!"; // stack area
                        
  return 0;
}

str0 points in the character string is constant region, but str0 itself is the pointer variable in the stack area, the variable is stored in a character constant region "Hello World!" the first address.

str1 is an array of characters, so str1 as string is stored in the stack area, where the use is merely a form of character array initialization, in fact, it can be written as follows:

char str1 [] = { 'H', 'e', 'l', 'l', 'o', '', 'W', 'o', 'r', 'l', 'd', ' ! ',' \ 0 '};

(4) the stack area: local variables, parameters, function return address, etc., by the system to manage, in the memory which is to address the low growth from high addresses, the size of the stack space is limited, as defined in a large stack when using an array or a deep recursive call, it is possible to stack overflow.

(5) heap area: from malloc, calloc, realloc function allocates space managed by ourselves, after every use, must be free to release the memory, otherwise, it will have a memory leak, memory after each release, although no longer occupy a piece of memory, but the corresponding pointer still points to this area, this pointer is a pointer field, so the release of memory, it is recommended to assign the pointer NULL. as follows:

int main () {
  int * p = (int *) malloc (100 * sizeof (int));
  / *
    Execute the statement
  * /
  free (p); // At this point p is still that memory, become wild pointer
  p = NULL; // assign NULL to p
  return 0;
}

3, C language I / O input and output

C language itself does not carry the input and output characteristics, so it's all I / O operations through system call. Fortunately, the C standard library, has given us a good package as a function of a number of I / O operations.

putchar (): the variable in a character constant output to the display screen;

Enter a character constant from the keyboard, this constant is the value of the function; getchar ();

printf (); put the keyboard in the various types of data, to control the output format to the display screen;

scanf (); various types of data input from the keyboard, and place the program variables;

puts (): the array variable in a string constant output to the monitor screen

gets (): Enter a string constant from the keyboard and put the program array

Some for the operation of the document, since anything can be seen as a file, standard input and output can also operate as a file, the file descriptor: standard input (0), standard output (1), standard error (2)

fputs (); output to a file

fgets (); input from a file

fscanf (); input file format

fprintf (); Output file format

Two other very important function, of course, derive their function is similar

sscanf (); various types of data extracted from a string.

sprintf (); to write formatted data to a string

Each function here does not explain, mainly on the formatting functions for analysis:

(1) when we want to convert to an integer or a string to an integer into a string, we generally think of atoi () or itoa () (non-standard function), but we can flow to achieve:

int main () {
    int num = 10;
    char str [10] = {0};
    sprintf (str, "% d", num); // int converted to char []
    num = 0;
    sscanf (str, "% d", & num); // convert string to int
    printf ( "num:% d str:% s \ n", num, str);

    return 0;
}

Conversion string transfer and other types: such as float, 16 hex, unsigned and so can be used to achieve flow.

(2) formatting functions in regular expressions

All formatting functions can customize their own scanset% [abc],% [a-z],% [^ abc],% [^ a-z], where [] within a matching character ^ represents negated set.

When we enter the string from the standard input with a possible space, the direct use scanf ( "% s", str); when they read space returns, then you can use regular expressions:

char str [100] = {0};
scanf ( "% [^ \ n]", str); // write until it encounters a carriage return

Just read from the standard input lowercase a-z, meet other characters Returns:

char str [100] = {0};
scanf ( "% [a-z]", str);

Usage other formatting functions are the same, not one by one example.

4, summary

From freshman to start learning C language there are four or five years, think: C language, the greatest success is that it is a pointer, but also the most prone to error, and want to understand C, you must master pointer. Although that language is only a tool, but it is the foundation. Perhaps you can say, is now JAVA world, and is filled with JAVA engineer recruitment; or you can say that is too low-level C, are now OOP era, and who will use the process-oriented ...... Do not forget that the operating system is what is written? It is C; concurrency nginx's C implementation is several times the C ++ implementation of the apache. No matter what programming language, good school, in-depth learning on the line, not because it is fashionable today to abandon learned yesterday.
     
         
         
         
  More:      
 
- RedHat Linux 9.0 under P4VP-MX motherboard graphics resolution of problems (Linux)
- Linux regex awk Comments (Linux)
- MySQL In can not be overridden with an internal connection (Database)
- Features and prevention methods elaborate network security grayware (Linux)
- The array of C language (Programming)
- Android recyclerview cardview (Programming)
- Java Foundation - The relationship between abstract classes and interfaces (Programming)
- Linux environmental performance data acquisition system (Linux)
- Proxmox VE implement KVM OpenVZ virtualization cloud computing (Server)
- Difference LVS three scheduling modes (Server)
- Nginx Keepalived Nginx monitoring scripts (Server)
- Perl loop (Programming)
- Linux 101 hack book reading notes (Linux)
- Github with .gitignore ignore specified file (Linux)
- Quickly build and install Linux KVM system (Linux)
- How to set up HTTPS policies for older browsers (Server)
- Steps to build MPICH2 development environment on CentOS 6.4 (Linux)
- Installation Mate Desktop in FreeBSD 10.1 (Linux)
- IBM Data Studio to use ---- window displays all rows (Database)
- CentOS permanently banned from running in the background PackageKit (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.