Difficulties in C Language (I switched it)

Source: Internet
Author: User
Tags fread variable scope

This article mainly introduces some important points I personally think during the C language review. A better grasp of these points will make the use of C more enjoyable. In addition, it will include some details and errors. The scope and storage categories of variables, functions, arrays, strings, pointers, files, and linked lists are involved. Some of the most basic concepts will not be explained here. I only hope to provide a little help for beginners of C language learning and machine learning.

Variable scope and storage class:

After learning about the basic variable types, we need to learn more about its storage classes and variable scopes.

Variable type Sub-category
Local variable Static variable (leave the function, and the variable value is retained)
Automatic Variable
Register variable
Global Variables Static variables (only available in this file)
Non-static variables (other files are allowed)

Change the angle

Variable type Sub-category
Static storage variables Static local variables (functions)
Static global variables (this file)
Non-static global/external variables (referenced by other files)
Dynamic Storage of Variables Automatic Variable
Register variable
Format parameters

Extern-type storage variables are often used to deal with multi-file problems. Defining extern-type variables in a file means that this variable uses other files. By the way, I encountered an out of memory error during the course setup, so I changed it to multiple files and then included it (pay attention to what I wrote *. h. Use "" Not needed <>) to make a certain effect. Static is a test point in the result of reading the program. Most of the time, the entire program will have multiple Defined variables in different functions, to check the value of the same variable at different locations. The main principle is to follow. You only need to use global variables (instead of those in main) for variables not defined in this function. When the global variables and local variables are renamed, local variables take effect, pay attention to the differences between static and automatic variables.

Function:

The most basic understanding of a function starts with the word "Main". At the beginning, I always thought it would be nice to write the statement together in Main. Why. In fact, this is because the function is not skilled enough, otherwise the use of the function will bring great convenience to our programming. We need to know the type of the return value of the function, the type of the parameter, and the form of calling the function. Prior function descriptions can also serve as a reminder. The so-called form parameter and real parameter, that is, the real parameter is written in brackets when the function is called. The function itself uses the form parameter, and uses the parallelogram to represent the passing parameter during the flowchart.

Another application example of the function is recursion. I started to have a headache and the response was always slow. According to the teacher's method, the recursive process was patiently and accurately drawn step by step, the learning effect is still relatively good, and we will think that the use of this recursion is quite clever. In fact, the famous Eight queens and tower of arms all use recursion.

Example:
Long fun (int n)
{
Long S;
If (n = 1 | n = 2) S = 2;
Else S = N-fun (n-1 );
Return S;
}
Main ()
{
Printf ("% lD", fun (4 ));
}

 

Array:

It can be divided into one-dimensional array and multi-dimensional array. If the storage method is table, it will be clear. In fact, it is to put the same type of variables together in order. Therefore, when processing a large amount of data (this is also the case in most cases), the array is widely used.

The actual application is inconvenient, and most of them are combined with pointers. I personally think that learning arrays are a foreshadowing to learning pointers to a greater extent. As the basis, you must understand several basic operations: array assignment, printing, sorting (Bubble sorting and selection sorting), and searching. These are all inevitable cycles. If you feel that the response is not enough, you can first expand the cycle a little bit, and you will become more and more familiar with it, in the future, when writing a function by yourself, we will first find out the internal rules and make better use of them. In addition, when an array is used as a parameter, it can be null in [] of one dimension, but the size must be specified in the first [] of two dimensions.

Bubble sort function:
Void bubble (int A [], int N)
{
Int I, J, K;
For (I = 1, I <n; I ++)
For (j = 0; j <n-I; j ++)
If (A [J]> A [J + 1])
{
K = A [J];
A [J] = A [J + 1];
A [J + 1] = K;
}
}

Sort by selection function:
Void sort (int A [], int N)
{
Int I, J, K, T;
For (I = 0, I <n-1; I ++)
{
K = I;
For (j = I + 1; j <n; j ++)
If (A [k] <A [J]) k = J;
If (K! = I)
{
T = A [I];
A [I] = A [k];
A [k] = T;
}
}
}

Semi-query function (original array order ):
Void search (int A [], int N, int X)
{
Int left = 0, Right = n-1, mid, flag = 0;
While (flag = 0) & (left <= right ))
{
Mid = (left + right)/2;
If (x = A [Mid])
{
Printf ("% d", X, mid );
Flag = 1;
}
Else if (x <A [Mid]) Right = mid-1;
Else left = Mid + 1;
}
}

Common AlgorithmsJudge the input, calculate the factorial, and perform any hexadecimal conversion in the fibanacci series.And so on..

String:

A string is actually an array (pointer). You do not need to add the "&" symbol in the input column of scanf because the character array name itself represents the address. It is worth noting that the '/0' at the end of the string, if not, the string may not print properly. Another problem is the definition and value assignment of strings. One of my comprehensive machine jobs was that string printing was always garbled. I found a problem in the upper and lower circles.

Char * Name;

Instead

Char name [10];

The former does not explain where it points, nor determine the size, leading to garbled errors, which are quite impressive.

In addition, the value assignment of strings also requires attention. If a character pointer is used, you can assign an initial value when defining it, that is

Char * A = "abcdefg ";

You can also assign values in the value assignment statement, that is

Char *;
A = "abcdefg ";

However, if a character array is used, the overall initial value can only be assigned at the time of definition, that is, char a [5] = {"ABCD"}, rather than the overall value in the value assignment statement.

The list of common string functions is as follows, which must be implemented by yourself:

Function Functions Function call form Remarks
String Copy Function Strcpy (char *, char *) Copy the latter to the former
String appending Function Strcat (char *, char *) After the latter is appended to the former, the former is returned, so the former space must be large enough.
String comparison functions Strcmp (char *, char *) If the former is equal to, less than, or greater than the latter, 0, positive, and negative values are returned. Note: It is not a comparison length, but a comparison of the size of the ASCII code, which can be used to sort by name and letter.
String Length Strlen (char *) Returns the length of the string, excluding '/0'. The Escape Character is a single character.
String type-> integer Atoi (char *)
Integer> string type ITOA (INT, char *, INT) Useful for course setup
Sprintf (char *, formatted input) Assign it to a string without printing it out. Easy to use during course setup

Note:The = or! String is not allowed! =, Only strings can be used to compare Functions

Pointer:

Pointers can be said to be the most important part of the C language. In fact, the name of this "pointer" has a very good understanding of this concept. First, you must know that the value of the pointer variable (that is, the value stored in the pointer variable) is the pointer (that is, the address ). In the definition form of pointer variables, "*" in the basic type * pointer variable name indicates a pointer variable pointing to the basic type, rather than the content. In future use, for example, when * PTR = A, "*" indicates that the content in the address pointed to by PTR is.

A typical and simple application example of pointers is the exchange of two numbers. Let's look at the following program,

Swap (int c, int D)
{
Int T;
T = C;
C = D;
D = T;
}
Main ()
{
Int A = 2, B = 3;
Swap (A, B );
Printf ("% d, % d", a, B );
}

This cannot realize the exchange of values between A and B. In fact, only the form parameters are exchanged in this function, which has no effect on the real parameters. Now, if you use pointer-type data as a parameter, the changes are as follows:

Swap (# 3333ff * P1, int * P2)
{
Int T;
T = * P1;
* P1 = * P2;
* P2 = T;
}
Main ()
{
Int A = 2, B = 3;
Int * ptr1, * ptr2;
Ptr1 = &;
Ptr2 = & B;
Swap (prt1, ptr2 );
Printf ("% d, % d", a, B );
}

In this way, the content of P1 and P2 is changed in SWAP, that is, the values of A and B are exchanged.

Pointer executableIncrement and decrement operationsCombined with the rules of the ++ operator, we can see that:

* ++ S

Get the content after adding 1 to the pointer variable

* S ++ Take the content indicated by the pointer variable and Add 1 s.
(* S) ++ Add 1 to the pointer variable

Pointers and ArraysIn fact, it is almost the same. The array name can be regarded as a constant pointer. In a one-dimensional array, PTR = & B [0], the following representation is equivalent:

A [3] is equivalent to * (a + 3)
PTR [3] is equivalent to * (PTR + 3)

Let's take a look at a function that uses pointers to implement atoi (string-> integer) by itself:

Int atoi (char * s)
{
Int Sign = 1, m = 0;
If (* s = '+' | * s = '-')/* determines whether a symbol exists */
Sign = (* s ++ = '+ ')? 1:-1;/* use the three-object operator */
While (* s! = '/0')/* operate on each character */
{
M = m * 10 + (* s-'0 ');
S ++;/* points to the next character */
}
Return M * sign;
}

Pointer variables pointing to multidimensional arrays are also widely used. For example, array a [3] [4], a represents the first address of the whole two-dimensional array, that is, the first address of row 0th, that is, a pointer variable. A + 1 is not simply adding 1 to the value, it represents not a [0] [1], but the first address of row 1st, & A [1] [0].

Pointer variables are commonly used to pass pointers as parameters to other functions, that isPointer to function.
Let's look at the following lines of code:

Void input (St *);
Void output (St *);
Void bubble (St *);
Void find (St *);
Void failure (St *);
/* Function declaration: all five functions use a pointer variable pointing to the st-type (pre-defined) structure as the parameter and have no return value. */

Void (* process [5]) (St *) = {input, output, bubble, find, failure };
/* When process is called, a total of five different functions are provided (pointing to the pointer array of the function )*/

Printf ("/nchoose:/n? ");
Scanf ("% d", & choice );
If (choice> = 0 & choice <= 4)
(* Process [choice]) (a);/* call the corresponding function to implement different functions *;/

In short, the pointer application is very flexible and extensive, not just in a few words. The above small examples are just an introduction. In actual programming, it will gradually discover the convenience and efficiency brought by the use of pointers.

File:


Function call form Description
Fopen ("path", "open mode ") Open a file
Fclose (File *) Prevent future misuse
Fgetc (File *) Read one character from a file
Fputc (CH, file *) Write the characters represented by CH into this file
Fgets (File *) Read a row from a file
Fputs (File *) Write a row to a file
Fprintf (File *, "Format String", output table column) Write data to a file
Fscanf (File *, "Format String", input table column) Read from File
Fwrite (address, sizeof (), N, file *) Write n sizeof big data in the address to the file.
Fread (address, sizeof (), N, file *) Read n pieces of sizeof big data in the file to the address.
Rewind (File *) Returns the file pointer to the file header.
Fseek (File *, X, 0/1/2) Move the file pointer. The second parameter is the displacement. 0 indicates moving from the beginning, 1 indicates moving from the current position, and 2 indicates moving from the end of the file.
Feof (File *) Determine whether the file ends


File Opening Method Description
R Open readable files
W Create a file for writing. If the file already exists, erase the original data.
A Open or create a file that appends data to the end of the file.
R + Open the file used to update data
W + Create a file for data update. If the file already exists, erase the original data.
A + Open or create a file for updating data, and append the data to the end of the file

Note:The above is used for text file operations. If it is a binary file, "B" is added after the above letter ".

The biggest purpose of using a file is to save the data. Therefore, when you want to use the data in a file, you need to read the data into a structure (generally, the data is stored in multiple structures for ease of management), and then perform operations on the structure. For example, file AA. data stores information such as scores of 30 students. When you need to traverse the information and output, sort, and search the scores, we will first read the information into a structure array, and then operate on this array. For example:

# Include <stdio. h>
# Include <stdlib. h>
# Define N 30

Typedef struct student/* defines an array of student scores */
{
Char * Name;
Int Chinese;
Int maths;
Int PHY;
Int total;
} St;

Main ()
{
St a [n];/* array storing n student information */
File * FP;
Void (* process [3]) (St *) = {output, bubble, find};/* three functions that implement related functions */
Int choice, I = 0;
Show ();
Printf ("/nchoose:/n? ");
Scanf ("% d", & choice );
While (choice> = 0 & choice <= 2)
{
Fp = fopen ("AA. dat", "rb ");
For (I = 0; I <n; I ++)
Fread (& A [I], sizeof (ST), 1, FP);/* read the information stored in the file one by one to the array */
Fclose (FP );
(* Process [choice]) (a);/* the pointer to the function mentioned earlier, select the operation */
Printf ("/N ");
Show ();
Printf ("/n? ");
Scanf ("% d", & choice );
}
}

Void show ()
{
Printf ("/n ***** choices: *****/n0.display the data form/n1.bubble it according to the total score/n2.search/n3.quit! /N ");
}

Void output (St * A)/* output the information stored in the file one by one */
{
Int I, T = 0;
Printf ("name Chinese maths physics total/N ");
For (I = 0; I <n; I ++)
{
T = A [I]. Chinese + A [I]. Maths + A [I]. PHY;
A [I]. Total = T;
Printf ("% 4 S % 8d % 8d % 8d % 8d/N", a [I]. name, a [I]. chinese, a [I]. maths, a [I]. phy, a [I]. total );
}
}

Void bubble (St * A)/* sorts the array and outputs The result */
{
Int I, pass;
St m;
For (pass = 0; pass <N-1; pass ++)
For (I = 0; I <N-1; I ++)
If (A [I]. Total <A [I + 1]. Total)
{
M = A [I];/* structure swapping */
A [I] = A [I + 1];
A [I + 1] = m;
}
Output ();
}

Void find (St *)
{
Int I, T = 1;
Char M [20];
Printf ("/nenter the name you want :");
Scanf ("% s", M );
For (I = 0; I <n; I ++)
If (! Strcmp (m, a [I]. Name)/* output the search result based on name matching */
{
Printf ("/nthe result is:/n % s, Chinese: % d, maths: % d, physics: % d, total: % d/N", m, A [I]. chinese, a [I]. maths, a [I]. phy, a [I]. total );
T = 0;
}
If (t)
Printf ("/nthe name is not in the list! /N ");
}

Linked List:
Linked List is another difficulty in C language. It involves nodes, dynamic space allocation, and so on. It is very suitable to use the structure as the node of the linked list, for example:

Struct Node
{
Int data;
Struct node * next;
};

Next is a pointer to its own structure, which connects nodes to form a linked list.

One of the major advantages of the linked list structure is the dynamic distribution of storage, which does not have to be determined during definition as an array, resulting in unnecessary waste. You can use the malloc and free functions to open up and release storage units. Among them, the malloc parameters are calculated using the sizeof operator.

The basic operations of the linked list are as follows:Create a linked list in front and back; Output A linked list; Delete nodes in the linked list; insert nodes in the linked listAnd so on.DrawingYou can visually understand the implementation process, such as creation and insertion.

Typedef struct Node
{
Char data;
Struct node * next;
} Node;/* node */

Create a linked list in the forward direction:
Node * Create ()
{
Char CH = 'a ';
Node * P, * H = NULL, * q = NULL;
While (CH <'Z ')
{
P = (node *) malloc (sizeof (node);/* force type conversion to pointer */
P-> DATA = CH;
If (H = NULL) H = P;
Else Q-> next = P;
Ch ++;
Q = P;
}
Q-> next = NULL;/* end of the linked list */
Return h;
}

 

Reverse build:

Node * Create ()
{
Char CH = 'a ';
Node * P, * H = NULL;
While (CH <= 'Z ')
{
P = (node *) malloc (sizeof (node ));
P-> DATA = CH;
P-> next = H;/* constantly move the head forward */
H = P;
Ch ++;
}
Return h;
}

 

Recursive output of the chain table in reverse order:

Void output (node * H)
{
If (H! = NULL)
{
Output (H-> next );
Printf ("% C", H-> data );
}
}

Insert nodes (a linked list already exists in ascending order ):

Node * insert (node * H, int X)
{
Node * New, * front, * Current = h;
While (current! = NULL & (current-> data <X)/* Find the inserted position */
{
Front = current;
Current = Current-> next;
}
New = (node *) malloc (sizeof (node ));
New-> DATA = X;
New-> next = current;
If (current = h)/* determines whether the header is to be inserted */
H = new;
Else front-> next = new;
Return h;
}

 

Delete a node:

Node * Delete (node * H, int X)
{
Node * q, * P = h;
While (P! = NULL & (p-> data! = X ))
{
Q = P;
P = p-> next;
}
If (p-> DATA = x)/* locate the node to be deleted */
{
If (P = h)/* determine whether to delete the header */
H = H-> next;
Else Q-> next = p-> next;
Free (p);/* release deleted nodes */
}
Return h;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.