Familiarity with C language (simple introduction)

Source: Internet
Author: User
Tags sprintf

First, Brief introduction

The goal of the C language is to provide a programming language that compiles, processes low-level memory, produces a small amount of machine code, and can run without any running environment support in an easy way. It has the following characteristics: simple and compact, flexible and convenient, rich operator, data type rich, flexible and practical expression, allowing direct access to physical address, the hardware to operate, generate high-quality object code, program execution efficiency, portability, and strong expression; but at the same time, encapsulation and grammar are not as good as other languages. Personally, in the practice and design of the algorithm, C language is a good choice, less memory, closer to the bottom, it is easy to implement a variety of data structures.

Second, the basic knowledge

1. Basic input and output

scanf function

defined in the header file stdio.h, it is a format input function that enters data into the specified variable from the keyboard in the user-specified format.

Function Prototypes:

int scanf (constchar *format,...);

Its invocation form is: scanf ("< format description string >",< variable address >), variable address requirements are valid, and the order of the format description is consistent.

The scanf () function returns the number of data items that were successfully assigned, and EOF is returned when an error is read to the end of the file.

Such as:

scanf ("%d%d", &a,&b);

If both A and B are read successfully, then the return value of scanf is 2.

Format specifier
Convert character (the part that is the% followed)
C Read single character
D-Read decimal integer
I-read decimal, octal, hexadecimal integer
e Read floating point number
E Read floating point number
F Read floating point number
G Read floating point number
G Read floating point number
O Read octal number
S-Read string
X-Read hexadecimal number
X-Read hexadecimal number
P Read pointer value
n the equivalent number of characters that have been read into the value
U-read unsigned decimal integer
[] Scan Character Set
% read% symbol (percent sign)
Description of additional format specifier character form modifiers
l/l length modifier Enter "Long" data
H-Length modifier input "short" data
W integer constant Specifies the width of the input data
* Indicates that this entry is not assigned to the corresponding variable after it is read into

Selective Scan Input Examples:

#include <stdlib.h>#include<stdio.h>int  main () {   int  a,b,c ;   scanf ("%d,%d,%d", a,b,c);         // input format is a,b,c   printf ("%d%d%d", a,b,c);         // output format is a b C (with spaces in the middle)   return 0 ;}

printf function

The printf () function is a formatted output function that is typically used to output information to a standard output device in a prescribed format. The printf () function is called in the format: printf ("< formatted string >", < Parameter table >). Parameters are used in a similar way to the scanf function


2.for Cycle

When you write a for loop, you need to be aware of declaring the initial variables and then using them in parentheses (different from C + +) in the following form

int I;for (i=0;i<size;i++) {//To do}

Using this form will make an error:


3. Common Header Files

The #include <stdlib.h>//stdlib header file is the standard library header file.

The stdlib.h defines five types, some macros, and common tool functions. Types such as size_t, wchar_t, div_t, ldiv_t, and lldiv_t, macros such as Exit_failure, Exit_success, Rand_max, and Mb_cur_max, etc., commonly used functions such as malloc (), Calloc (), realloc (), free (), System (), Atoi (), ATOL (), Rand (), Srand (), exit (), and so on. Specific content you can open the compiler's include directory inside the stdlib.h header file to see.

#include <stdio.h>//includes some input and output functions, such as scanf,printf


4. String

You can use character arrays to represent strings, such as

#include <stdlib.h>#include<stdio.h>int  main () {    char str[  ]="HelloWorld";  // only used when initializing     printf (str);     return 0 ;}

You can use the STRCP function to copy the string that gets the input

#include <stdio.h>#include<string.h>intMain () {Charstr1[ A] ="Hello"; Charstr2[ A] =" World"; Charstr3[ A]; intLen; /*copy str1 into STR3*/strcpy (STR3, str1); printf ("strcpy (STR3, str1):%s\n", STR3); /*concatenates str1 and str2*/strcat (str1, str2); printf ("strcat (str1, str2):%s\n", STR1); /*Total lenghth of str1 after concatenation*/Len=strlen (STR1); printf ("strlen (str1):%d\n", Len); return 0;}

Output

strcpy (STR3, str1):  hellostrcat (STR1, str2):   Helloworldstrlen (str1):  10

  

Convert a number to a string

A. The ability to convert integers to strings and to be compatible with ANSI standards is to use the sprintf () function

#include <stdio.h># include<stdlib. H>voidMain (void);voidMain (void){    intnum = -; Charstr[ -]; sprintf (str,"%d", num); printf ("The number ' num ' is%d and the string ' str ' is%s. \ n", num, str);}

B. Use the FCVT () function to convert a floating-point value to a string example:

# include <stdio. H># include<stdlib. H>voidMain (void);voidMain (void){    Doublenum =12345.678; Char*Sir; intDEC_PL, sign, ndigits =3;/* Keep 3 digits of precision. */str = FCVT (num, ndigits, &DEC-PL, &sign);/* Con Vert the float to a string. */printf ("Original number;  %f\n ", num);                                                    /* Print the original floating-point Value. */printf ("converted string;    %s\n ", str); /* Print The converted string ' s value. */printf ("Decimal Place:%d\n", DEC-PI); /* Print The location of the decimal point.            */printf ("Sign:%d\n", sign);                                                 /* Print the sign. 0 = positive, 1 = negative. * /}

The FCVT () function and the itoa () function have several significant differences. The FCVT () function has 4 parameters: the first parameter is the floating-point value to be converted, the second argument is the number of digits to the right of the decimal point in the conversion result, and the third argument is a pointer to an integer that returns the position of the decimal point in the conversion result, and the fourth argument is a pointer to an integer. The integer used to return the symbol for the result of the conversion (0 corresponds to a positive value and 1 corresponds to a negative value).

5. Arrays, how to use two-dimensional or high-dimensional arrays, how to use it to represent the matrix, how to use it to represent the diagram

1, two-dimensional array concept

In C, a two-dimensional array is actually a special one-dimensional array, and each of its elements is also a one-dimensional array. Therefore, the subscript form of the two-dimensional array is correctly spelled as follows: Int arrays[i][j]. Array elements are stored in row order, so the rightmost array subscript (column) changes fastest when the tree is accessed in a stored order.

2, two-dimensional arrays as function parameters

Rule: If a two-dimensional array is passed as an argument to a function, the number of columns in the array must be indicated in the parameter declaration of the function, the number of rows in the array is not too large, and can be specified or unspecified. Because a function call is passed a pointer to a one-dimensional array that is sufficient for the row vector. So the two-dimensional array is correctly spelled as a function parameter as follows:

void Func (int array[3][10]);

void Func (int array[][10]);

Because the number of rows in an array is irrelevant, you can also write the following form:

void Func (int (*array) [ten]); Note that *array needs to be enclosed in parentheses.

This form of declaration argument is a pointer to a one-dimensional array with 10 elements. Because the priority of [] is higher than the priority of *, the *array must be enclosed in parentheses, otherwise it becomes

void Func (int *array[10]);

This time the argument is equivalent to declaring an array with 10 elements, each of which is a pointer to an integer object.

However, it is not possible to omit the size of the second or higher dimension, as the following definition is illegal:

void Func (int array[[]);

Because arguments are passed from the beginning address of the array, stored in memory by array rules (stored in rows), not branches and columns, if the number of columns is not specified in the formal parameter, the system cannot determine how many rows should be, and cannot specify only one dimension without specifying a second dimension, the following is wrong:

void Func (int array[3][]);

The real parameter group dimension can be greater than the shape parameter group, for example, the shape parameter group is defined as:

void Func (int array[3][10]);

code example:

Error-prone notation:

#include <cstdio>voidPrintint*arr[3]) {printf ("%d\n", arr[0][0]);}intMain () {intarr[2][3] = {1,2,3,4,5,6};    Print (arr); return 0;}

Correct wording:

1#include <cstdio>2 voidPrintint(*arr) [3])//enclose the pointer in parentheses.3 {4printf"%d\n", arr[0][0]);5 }6 7 intMain ()8 {9     intarr[2][3] = {1,2,3,4,5,6};Ten print (arr); One     return 0; A}

6. Dynamic allocation of space issues, how to assign, whether to specify size

Dynamic arrays:

int *arr= (int *) malloc (size*sizeof (int)); Where size is a numeric size, you can depend on the size you actually need


7. Be aware of what is different from C + +

C programs that cannot be compiled in C + +

7.1 in C + +, calling this function before a function declaration produces a compilation error. In C, however, it is possible to compile normally.

#include <stdio.h>int  main () {   //  foo () is called before its declaration/ Definition}  int  foo () {   printf ("Hello" );    return 0 ; }

7.2 in C + +, pointing the constant pointer to a constant produces a compilation error, but is allowed in C.

#include <stdio.h>intMainvoid){    int Constj = -; /*The below assignment is invalid in C + +, results in error in C, the compiler *may* throw a warning, but casting is implicitly allowed*/    int*ptr = &j;//A Normal pointer points to constprintf ("*ptr:%d\n", *ptr); return 0;}

7.3 in C, void pointers can be assigned directly to other type pointers, such as int *, char *, but are not allowed in C + +.

#include <stdio.h>int  main () {   void *vptr;    int //    return0;}

7.4 Constants in C + + must be initialized, but are optional in C.

#include <stdio.h>int  main () {    constint A;   // Line 4    return 0 ;}

The 7.5 C + + specific keyword is allowed in C. Although this is the case, the actual programming process should try to avoid these problems.

#include <stdio.h>int main (void) {    intnew5;  // new is a keyword in C + +, but not in C    printf ("%d"new);}

7.6 C + + has more stringent type checking. For example, the following program can pass in C, but cannot be compiled in C + +.

#include <stdio.h>int  main () {    char333;    printf ("c =%u", c);     return 0 ;}

Familiarity with C language (simple introduction)

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.