C study notes

Posted by pgrevents on Tue, 01 Mar 2022 06:10:13 +0100

C Primer Plus (6th Edition) Chinese version

Chapter 1 initial C language

Compiler: translate high-level language into digital instruction code (machine language)

Compilation: gcc source code c -o executable code exe

. c: indicates the source code file

. exe: executable code

getchar(): read one character

Chapter 2 overview of C language

include: it has the function of sharing

stdio.h: Standard part of C compiler software package, standard input and output header file

#include: this line of code has the function of preprocessing, which is called header file

Annotation style: / / is a new style annotation in C99, which is widely used in C + + and Java

#include <stdio. h> / * header file*/
/**
 * @brief main Function, the first function called by C language
 * 
 * @return float main The function returns a float
 */
float main (void) {  //Not up to standard
    printf("I am");  /*Read an Enter key*/
    return 0;
}

void: the parameter is null

int: the return value is an integer

int main(void)  //Fixed standard form
int main()      //C90 standard is acceptable, C99 and C11 standards are not acceptable, and the standard is becoming more and more strict

2.1 function definition - multiple

  1. Declare function (function prototype)
  2. Define function

Their parameters and return values are consistent

#include <stdio.h>
int buffer(void);  /*Declare buffer function*/

int main(void)
{
 printf(buffer() + "Yes, Let us jump up right in .");/*Using the buffer function*/
 return 0;
}

int buffer(void) /*The definition of buffer function must be consistent with the declared function*/
{
    printf("Are you ready ?\n");
    return 0;
}

be careful

#define DAYS_PER_YEAR 365 (✔)

#define DAYS_PER_YEAR = 365 (❌)

Chapter 3 data and C

%. 2f: output the last two decimal places

%lf: print double data

%ld: Print long data

%hd: print short data

%u: Print unsigned type

unsigned: non negative

_ Bool: Boolean type (integer)

_ Complex: complex

_ Imaginary: imaginary number

3.1 storage method - floating point number

Sign bitFractional partIndex part
+.31415921

Result: 3.141592

3.2 representation - hexadecimal

Octal: start with 0

Hex decimal: starts with 0x or 0x

3.3 display mode - binary

  • Display the number in xx decimal

    • decimal:% d
    • Octal:% o (oh ~)
    • Hex decimal:% x
  • Prefixed decimal number display

    • Octal:%#o
    • Hex decimal:% #x% #x

code

#include <stdio.h>

int main (void)
{
    int x = 100;  /*It can be replaced with 0100 and 0x100 for demonstration*/

    printf("Hexadecimal display\n");
    printf("\tdec = %d; octal = %o; hex = %x\n", x, x, x);
    
    printf("Prefixed decimal number display\n");
    printf("\tdec = %d; octal = %#o; hex = %#x\n", x, x, x);
    return 0;
}

result

Hexadecimal display
dec = 100; octal = 144; hex = 64
Prefixed decimal number display
dec = 100; octal = 0144; hex = 0x64

3.4 _Bool type

C99 standard added_ Bool type, C language uses 1 to represent true and 0 to represent false;

So_ Bool is actually a 1-bit integer type (1 byte, 8 bits)

  • Portable type
    • stdint.h: The compiler replaces int or long with a type that matches the current system
    • inttypes.h: Solve int32_t whether to use% d or% ld for printout is different

3.5 floating point

float: it can represent at least 6 significant digits, usually 32 bits, of which 8 bits are used to represent the symbol and index, and 24 bits are used to represent the non exponential part, also known as mantissa or significant number

double: it can represent at least 10 significant digits. Usually, the extra 32 bits of 64 bits represent the non exponential part, which increases the number of significant digits (i.e. improves the accuracy) and reduces the rounding error

3.6 overflow

code

#include <stdio. h> / * added two header files*/
#include <float. h> / * overflow of floating point number = = > FLT_ MAX,FLT_MIN*/
#include <limits. h> / * integer overflow = = > int_ MAX*/

/*Integer overflow + floating point overflow and underflow*/
int main (void)
{
    /*1. Integer overflow*/
    int big_int = 2147483647;
    printf("The big int data is %d\n", ++big_int);

    /*2. Floating point overflow*/
    float big_float = 3.4e38;
    printf("The big float data is %f\n", big_float * 10);

    /*3. Floating point underflow*/
    float small_float = 10.0 / 3;
    printf("The small float data is %f\n", small_float);

    printf("The MAX int data is %ld\n", INT_MAX);
    printf("The MAX int data is %ld\n", INT_MIN);
    printf("The MAX float data is %f\n", FLT_MAX);
    printf("The MIN float data is %f\n", FLT_MIN);
    return 0;
}

result

The big int data is -2147483648
The big float data is 1.#INF00
The small float data is 3.333333
The MAX int data is 2147483647
The MAX int data is -2147483648
The MAX float data is 340282346638528860000000000000000000000.000000
The MIN float data is 0.000000

Chapter 4 string and formatting I / O

4.1 strlen(),sizeof()

  • strlen() function

    • Read the end of string \ 0, string size does not include \ 0
    • The size calculation of char array is the same as above
  • sizeof() function

    • The size contains the * * \ 0 * * ending character after the string
    • char name[40] function reads the byte size of char type array
  • int values[5]

    • Sizeof (values) = = > return 5x4 = 20
    • sizeof(values) / sizeof(values[0]) ==> 5

Not applicable to 2D array traversal

code

#include <stdio.h>
#include <string. h> / * header file of strlen function*/
#define NAME "Liao Shuxing"

int main (void)
{
    char name[40] = NAME;  /*C There is no string type in the language. String storage usually ends with \ 0 and does not calculate \ 0*/
    printf("What is your name?\n My name is %s\n", name);

    printf("How about name's length?\n It is %d\n", strlen(name));  /*End of string / 0 encountered = = = > string size*/
    printf("How about name's size?\n It is %d\n", sizeof(name));  /*Get = = = > char array size*/
    return 0;
}

result

What is your name?
My name is Liao Shuxing
How about name's length?
It is 6
How about name's size?
It is 40

4.2 characters and strings

'x' is a character"x" is a string
Storage formxX\0

4.3 const qualifier

Source: const keyword added in C90 standard

Function: limit a variable to read-only

Advantage: more flexible than #define

const int MONTHS = 12;  /*Correct definition, MONTHS cannot be modified in the program*/

#The difference between define and const (reference link)

4.4 conversion description - field width

Conversion Description:% s% d% F

%4d: if the printed number does not have 4 digits, it will be filled in with spaces

%5.2f: field width 5 digits, 2 digits after the decimal point

%10.2s: field width 10 digits, significant digits 2 digits, right aligned

%-10.2s: field width is 10 digits, significant digits are 2 digits, - indicates left alignment

%-03.2d: the field width is 3 digits and the significant digits are 2 digits. Fill the field width with 0 instead of space. If it exceeds the field width, it does not need to be filled and is displayed directly

p72

code

#include <stdio.h>

int main (void)
{
    char num[40] = "Liao Shuxing";

    printf("|%10.2s|\n", num);  /*It can be replaced with% 10.4s for demonstration, and Chinese usually takes up 2 bytes*/
    printf("|%-10.2s|", num);
    return 0;
}

result

|Liao|
|Liao|

code

#include <stdio.h>
#define NAME "Liao Shuxing"
#define ADDRESS "group xx, village xx, xxx Town, Wugang City, Hunan Province"
#define PHONE_NUMBER "one hundred and sixty-six xxxx7152"

int main (void)
{
    printf("%-20s %-40s %-20s\n", "full name", "address", "phone number");
    printf("%-20s %-40s %-20s\n", NAME, ADDRESS, PHONE_NUMBER);
    return 0;
}

result

full name                 address                                  phone number
 Liao Shuxing               Wugang City, Hunan Province xxx town xx village xx group                166xxxx7152
  • Neat and beautiful output
// 1. Normal output
printf("%d\t%d\t%d\n", 312, 2344, 136);
printf("%d\t%d\t%d\n", 400, 234, 3412);

// 2. Use fixed field width for output. The character width is 6. Make up for insufficient space. The default is right alignment
printf("%6d\t%6d\t%6d\n", 312, 2344, 136);
printf("%6d\t%6d\t%6d\n", 400, 234, 3412);

---Comparison of output results---
312	2344	136
400	234	3412
   312	  2344	   136
   400	   234	  3412

4.5 precision freedom

float salary = 123.00;
int width, precision;
printf("Enter a width and a precision:\n");
scanf("%d %d", &width, &precision);
printf("%*.*f", width, precision, salary); // *Indicates the width of the field, and the precision is controlled by keyboard input

%Input to s and scanf functions

char name[30];
printf("Input one name:");
scanf("%s", name); // Only the part will be read, and the writing will stop when there is a blank space
printf("%s", name);
return 0;
---Output results---
Input one name: carter I love you
carter

4.6 Scanf character array

char type array: when using scanf input, it is not required in the front==&==

Scanf is not the most commonly used input!!!

  • %s: Do not receive strings with white space, and terminate at the space
  • %c: Space characters can be accepted and only one character can be read

Reason: when the first blank is encountered, scanf thinks that the work is completed, and the subsequent data will not be written to the current variable, but only saved in the input buffer!!!

be careful

scanf("%c", &ch);  /*Read from the first character in the input*/
scanf(" %c", &ch); /*Read from the first non white space character in the input*/

code

#include <stdio.h>

int main (void)
{
    int age;
    float assets;
    char pet[30];  /*This is a string*/

    printf("Please input your value:");
    scanf("%d", &age);
    scanf("%f", &assets);
    scanf("%s", pet);  /*Character arrays are not required&*/


    printf("age = %d\n", age);
    printf("assets = %f\n", assets);
    printf("pet = %s\n", pet);

    char c;
    printf("Enter a character:\n");
    
    getchar();  /*You must have this one, or you'll skip the next input*/
    
    scanf("%c", &c);  /*If the & symbol is required, you can enter a blank character*/
    printf("[%c]", c);  /*Can receive blank*/
}

result

Please input your value:12 11.90 hello world~
age = 12
assets = 11.900000
pet = hello

Enter a character:

[ ]

Note: Hello world = = = > only read hello

4.7 flexible application of% * d-modifier

  • Input through scanf to customize the field width

code

#include <stdio.h>

int main (void)
{

    int width, number;  /*width Provide the field width, and number is the number to be printed*/
    printf("Please input the String's width:_____\b\b\b");
    scanf("%d", &width);

    printf("\nThe number is ");
    getchar();  /*To prevent flashing, it is often added on scanf*/
    scanf("%d", &number);

    printf("Format output:[%-*d]", width, number);
    getchar();/*prevent. exe executable flash back problem, you must get two, ruthless*/
    getchar();/*prevent. exe executable flash back problem. If there are characters in the cache, use getchar() to empty the cache. It is best to use sequential*/
    
    return 0;
}

result

Please input the String's width:_ 9__

The number is 10
Formatted output: [10]

4.8 skip String and get Int type after

code

#include <stdio.h>

/*Enter catch 22 skip string catch read value=22*/
int main (void)
{
    int value;
    printf("Input String is ");
    scanf("%*s %d", &value);  /*Ignore the string and take the following Int data*/

    printf("value = %d", value);
    return 0;
}

demonstration

Input String is value 11
value = 11

4.9 String character length calculation

  • printf function: be careful not to wrap lines
  • strlen function

code

#include <stdio.h>
#include <string.h>

/*
Get string size
①Using the printf function
②Using the strlen function
*/
int main (void)
{
    char name[20];
    printf("Input Your name:");
    scanf("%s", name);

    int lenthByPrintf, lenthByStrlen;

    lenthByPrintf = printf("%s", name);  /*Printf The returned value records the number of characters = = = > be careful not to wrap lines*/
    lenthByStrlen = strlen(name);  /*Strlen Function to obtain the number of characters, you need to add the header file string h*/

    printf("\nlenthByPrintf is %d, lenthByStrlen is %d", lenthByPrintf, lenthByStrlen);
    return 0;
}

demonstration

Input Your name:carter
carter
lenthByPrintf is 6, lenthByStrlen is 6

be careful

lenthByPrintf = printf("%s", name);     ===> len = 6
lenthByPrintf = printf("%s\n", name);   ===> len = 7 (Line breaks are also calculated)

Chapter 5 operators, expressions and statements

5.1 division operation

integer ➗ Integer = integer

Floating point number ➗ Floating point number = floating point number

code

#include <stdio.h>

/*Division operation*/
int main (void)
{

    int a = 1/3;
    float b = 1/3;
    float c = 1.0/3.0;

    printf("int a = %d\n", a);
    printf("float b = %.2f\n", b);
    printf("float c = %.2f\n", c);
    return 0;
}

demonstration

int a = 0
float b = 0.00
float c = 0.33

5.2 + + operation

problem

  • Is x = x + 1 equivalent to + + X? What about x + +?
  • x must be a modifiable value

Common mistakes

#include <stdio.h>
#define b 2

int main (void)
{
    const int a  = 1;
    printf("%d", a++);  /*Where a is constant and immutable*/
    printf("%d", b++);
    
    return 0;
}

result

Compilation error

  • Expressions a, b must be modifiable values

++a and b++

int number = 1;
printf("number=%d", number--); // Suffix mode - > output 1
printf("number=%d", --number); // Prefix mode - > output - 1
// ++x; <== Equivalence = = > x = x + 1;

Question

++num*num
    num*num++
    The difference between them???

sizeof: returns the size of the operand in bytes

  • Return value type: size_t (unsigned integer type)

side effect

  • Main purpose of statement
printf() \\ The side effect is the information displayed
int i;
i = 1; \\ The side effect is to change the variable i Change the value of to 1

sequence

  • End of full expression
  • The semicolon in the statement is the mark of the sequence point

5.3 cast type

int mice = (int) 1.3 / (int) 1.7;

5.4 parameter classification

C99 standard stipulates:

  • Argument: argument (with fixed value, such as a with 5 and int a = 1)
  • Parameter: parameter (int a)

Chapter 6 C control statement: loop

Only 0 in Arabic numerals indicates false

#include <stdio.h>

int main(void)
{
    int n = 3;

    while(n)
        printf("%2d is true!\n", n--);
    
    printf("%2d is false!\n", n);
    return 0;
}

The results are as follows:
 3 is true!
 2 is true!
 1 is true!
 0 is false! ---Only 0 indicates false

_ Bool type

  • _ Bool type is used to store int type
    • The number deposited is of type int, we**__ Bool will be set to 1**
    • Non int type stored_ Bool will be set to 0
    • Use stdpool h===> bool
#include <stdio.h>

int main(void)
{
    long num;
    long sum = 0L;
    _Bool input_is_good;
    
    printf("please input a number:\n");
    input_is_good = (scanf("%ld", &num) == 1);
    
    while (input_is_good) {
        sum = sum + num;
        printf("Please enter next integer (q to quit) :\n");
        input_is_good = (scanf("%ld", &num) == 1);
    }

    printf("Those integers sum to %ld.\n", sum);
    return 0;
}
======Operation results======
please input a number:
12
Please enter next integer (q to quit) :
12
Please enter next integer (q to quit) :
1.1
Please enter next integer (q to quit) :
Those integers sum to 25.
    
=====Conclusion: input int value_Bool Will be 1, continue iteration!!! Other types exit.=====

6.1 return value of scanf function

Scanf() function

  • When console input matches% ld
    • Match, return value is 1
    • Mismatch, return value is 0

6.2 operator priority

Arithmetic operators > relational operators > assignment operators

  • Arithmetic operators > relational operators
    • x > y + 2 ===> x > (y + 2)
  • Relational operators > assignment operators
    • x = y > 2 ===> x = (y > 2)

6.3 while loop

for (; test; ;)
while (test)	/*They have the same effect*/

Chapter 7 C control statement: branch and jump

7.1 printing% symbols

  • %%
int main (void)
{
    printf("%%");
    return 0;
}

code

#include <stdio.h>
#define FORMAT "%s! C is pretty good!\n"
#define PERCENT '%'

int main (void)
{
    printf(FORMAT, FORMAT);
    printf("%c", PERCENT);
    
    return 0;
}

result

%s! C is pretty good!
! C is pretty good!
%

7.2 getchar() and putchar()

getchar: no parameter, return the next character from the input queue

putchar: there are parameters. It has the same effect as printf, but can only receive a single character

code

#include <stdio.h>

int main (void)
{
    char ch;

    printf("Input your name: ");
    scanf("%c", &ch);
    ch = getchar();  /*Gets the next character entered*/
    
    printf("ch = [%c]\n", ch);
    return 0;
}

demonstration

Input your name: carter
ch = [a]

code

#include <stdio.h>

int main (void)
{
    char ch;
    ch = getchar();
    
    printf("ch = [%c]", ch);
    return 0;
}

demonstration

q
ch = [q]

Combined use

#include <stdio.h>
#define SPACE ' '

/*getchar And putchar*/
int main (void)
{
    char ch;
    ch = getchar();  /*Get a character*/

    while (ch != '\n')  /*A flag that ends with a newline character*/
    {
        if (ch == SPACE)
            putchar(ch);  /*If the current character is a space, it will not change*/
        else
            putchar(ch + 1);  /*Non space, print ASCII plus 1 characters*/

        ch = getchar();   /*Continue to get the next character*/
    }
    putchar(ch);  /*Print line breaks*/
    return 0;
}

demonstration

CALL MY NAME.
DBMM NZ OBNF/

7.3 ctype. Character function of H series

Enter a string of characters, only convert all letters, and keep the others as they are!

Problem: if the if condition is passed, it is too cumbersome to list all possibilities

Solution: ctype The H header file contains a series of functions that specifically handle characters

Page156

code

#include <stdio.h>
#include <ctype. h> / * header file of characters specially processed in C language*/

#define SPACE ' '

int main (void)
{
    char ch = getchar();  /*Read one character*/

    while ( ch != '\n')
    {
        if (!isalpha(ch))  /*It's not a condition that the letters remain as they are*/
            putchar(ch);
        else
            putchar(ch + 1);
        
        ch = getchar ();
    }
    putchar(ch);
    return 0;
}

result

LOOK! It's a programmer!
MPPL! Ju't b qsphsbnnfs!

7.4 multiple selection else if

  • else if in your imagination
#include <stdio.h>

int main (void)
{
    int a;
    printf("Input a number: ");
    scanf("%d", &a);

    if (a < 0)
        printf("a<0\n");
    else if (a < 10)
        printf("a It's a single digit\n");
    else if (a < 100)
        printf("a It's double digits");
    else
        printf("a > 100");

    return 0;
}
  • else if in practice
#include <stdio.h>

int main (void)
{
    int a;
    printf("Input a number: ");
    scanf("%d", &a);

    if (a < 0)
        printf("a<0\n");
    else
        if (a < 10)
            printf("a It's a single digit\n");
        else
            if (a < 100)
                printf("a It's double digits");
            else
                printf("a > 100");
    return 0;
}

7.5 iso646.h header file

C99 standard adds replaceable logical operators (& &, |,!) English spelling

Traditional writingiso646.h
&&and
||or
!not

7.6 conditional operators?

The only ternary operator in C language

x = (y < 0) ? y : -y
    
If y < 0 ===> x = y;
If y >= 0 ===> x = -y;

7.7 cycle assist: continue and break

continue: skip the rest of this iteration and go directly to the next cycle

break: terminates the loop that contains it

goto: basically not used

C primer plus (6th Edition) P172

Chapter 8 character input / output and input verification

8.1 input verification

  • Nonnegative integer
long n;
scanf("%ld", &n);
while (n >= 0)
{
    /*expression*/
    scanf("%ld", &n);
}
  • Integer type & nonnegative
long n;
while ((scanf("%ld", &n)) == 1 && n >= 0)
{
    scanf("%ld", &n);
}

Chapter 9 functions

9.1 pointer data exchange

code

#include <stdio.h>
void integerChange(int * x, int * y);

int main (void)
{
    int x = 10;
    int y = 11;
    printf("Before exchange: x = %d y = %d\n", x, y);

    integerChange(&x, &y);
    printf("After exchange: x = %d y = %d\n", x, y);

    return 0;
}

/*Data exchange*/
void integerChange(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

result

Before exchange: x = 10 y = 11
 After exchange: x = 11 y = 10

9.2 declaration and definition of functions

Three methods

/*Three methods of function declaration*/
#include <stdio.h>

/*ANSI Previous formal declaration function prototype*/
void dibs();  /*Type 1: old style function declaration*/

/*ANSI C Formal declaration function prototype*/
void sum01 (int a, int b);  /*Type 2: standard form*/
void sum02 (int, int);  /*Type 3: omit variable name*/

int main (void)
{
    dibs(2, 3);
    sum01(3, 4);
    sum02(4, 5);

    return 0;
}

/*Method 1*/
void dibs(x, y)
int x, y;
{
    printf("x + y = %d\n", x+y);
    return;
}

/*Method 2*/
void sum01 (int a, int b)
{
    printf("a + b = %d\n", a+b);
    return;
}

/*The third method*/
void sum02 (int a, int b)
{
    printf("a + b = %d\n", a+b);
    return;
}

result

x + y = 5
a + b = 7
a + b = 9

Ultimate method

/*Function declaration definition integration*/
#include <stdio.h>

void sum (int a, int b)
{
    printf("a + b = %d", a + b);
    return;
}

int main (void)
{
    sum(2, 3);
    return 0;
}

result

a + b = 5

Chapter 10 multidimensional array

10.1 pointers and arrays

ar[i] == *(ar+1) == *++ar

Value according to the first address

#include <stdio.h>
void sum (int * firstAddr, int arraysLen);

int main (void)
{
    int arrays[5] = {1, 2, 3, 4, 5};

    int arraySize = sizeof(arrays) / sizeof(arrays[0]);  /*Array size acquisition*/
    printf("Array size:%d\n", arraySize);

    printf("arrays = %#p\n", arrays);
    printf("&arrays[0] = %#P \ n ", & arrays [0]); / * are equivalent*/

    sum(&arrays[0], arraySize);
    return 0;
}

/**
 * @brief Calculate the sum of numbers in the array
 *  firstAddr: First address
 *  arraysSize: Array size
 */
void sum (int * firstAddr, int arraysSize)
{
    int total = 0;

    for (int i = 0; i < arraysSize; i++, firstAddr++)  /*Current address: firstAdrr next data address: firstAdrr + 1*/
    {
        printf("The first%d number\t Address:%#p value =% d\n", i + 1, firstAddr, *firstAddr);
        total += *firstAddr;
    }
    printf("the sum=%d", total);
    return;
}

result

Array size: 5
arrays = 0X000000000061FE00
&arrays[0] = 0X000000000061FE00
Number of addresses: fe61000001
Address of the second number: 0X000000000061FE04 value = 2
3rd number address: 0X000000000061FE08 value = 3
Number 4 address: 0X000000000061FE0C value = 4
Number 5 address: 0X000000000061FE10 value = 5
Sum = 15

10.2 const and pointer

be careful

int values[3] = {1,2,3};
const int *ptr = values;
ptr++;  /*No problem, point to values[1]*/
printf("%d", *ptr); ===>Output 2
    
    
const int a = 1;
a++;  /*There's something wrong. a is an immutable constant*/

*Prevail, left value and right pointer

  • const int * ptr

    • The address pointed to by the pointer can be modified, such as ptr + +, ptr = & values [2] ✔
    • The value pointed to cannot be modified, for example: * ptr = 4 ❌
  • int * const ptr

    • The address pointed to cannot be modified, such as ptr++ ❌
    • The value pointed to can be modified, such as: * ptr = 4 ✔
  • const int * const ptr

    • The address pointed to cannot be modified, such as ptr++ ❌
    • The value pointed to cannot be modified, for example: * ptr = 4 ❌

10.3 pointers and multidimensional arrays

int zipoo[4][2]

Zipoo array name: address of the first element * * & zipoo [0]**

zipoo[0]: & zipoo[0] [0] address

*(zipoo[0]): zipoo[0] [0] value

*Zipoo: & zipoo [0] [0] address

**Zipoo: zipoo[0] [0] value

10.4 pointer to multidimensional array

int (*ptr) [2]: ptr points to an array containing two int type values

int * ptr [2]: ptr is an array containing two pointer elements

equivalence relation

zippo[m][n] == *(*(zippo + m) + n)
pz[m][n] == *(*(pz + m) + n)
int pt[][4];  //An array pointer containing four type values
int [][4];  //Array names can be omitted
int (*pr)[4];  //The two are equivalent

Formal parameter declaration

int sum (int ar[][], int rows);  //Error declaration
int sum (int ar[][4],int rows);  //Correct statement
int sum (int ar[3][4], int rows);  //Correctly declared, 3 will be automatically ignored by the compiler, as above
int sum (int (*ar)[4], int rows);  //ditto

10.5 variable length array

C99 adds variable length array, which is a new feature of C language

  • Variable length array: dynamic allocation
  • Normal array: static allocation

Function declaration

int sum (int rows, int cols, int ar[rows][cols]);  /*Standard form, pay attention to the order and cannot be modified*/
int sum (int, int, int ar[*][*]);  /*C99/C11 The standard stipulates that the formal parameter name in the prototype can be omitted, but the array must be used ✳ Replace omitted dimensions*/

10.6 compound literal

  • Advantages: it is not necessary to create an array before passing information into a function. It is a typical usage of compound literal
int diva[2] = {10, 20};
(int [2]) {10, 20};  /*Anonymous function*/

int sum ((int [2]) {10, 20, 30}, 3);
/*
 Anonymous function at this time:
    ①Is an array containing three int type values, similar to the array name;
    ②It is also the address of the first element of the array;
*/

Chapter 11 string and string function

11.1 string array

  • Character array: a copy containing the literal value of a string

  • String: ends with \ 0

  • Pointer notation: has incremental operations++

  • Pointer array

    • Advantages: only display string, more efficient
    • Disadvantages: string literals cannot be changed
  • Normal array

    • Advantages: easy to change operation
    • Disadvantages: high memory consumption

If you want to change a string or make room for string input, do not use a pointer to the literal of the string

p281

11.2 string input function

11.2.1 gets() function

scanf() and conversion description% s can only read one word. The gets() function reads the entire line of input and ends when a newline character is encountered.

  • Add an empty character after the read character to make it a string.

  • Do not store line breaks

code

#include <stdio.h>
#define MAX 4

int main (void)
{
    char str [MAX];
    printf("Please enter a string:");
    gets(str);
    puts(str);
    return 0;
}

problem

  • When the size of the input string far exceeds the maximum storage capacity of str MAX-1, a warning will appear ⚠
  • buffer overflow
    • That is, the extra characters exceed the specified target space. These extra characters only occupy unused memory and will not cause problems immediately. If they erase other data in other programs, the program will terminate abnormally; Or other unsafe conditions. ⚠

11.2.2 fgets() function

The fgets() function solves the problem of buffer overflow by limiting the number of characters read in through the second parameter.

  • The second parameter n: the maximum number of characters to be read. The maximum number of characters to be read is n-1
  • Store line breaks
  • The third parameter indicates the file to be read in. Keyboard reading (stdin standard input)
  • fputs() function: stdout (standard output) does not wrap
  • Read error: NULL returned

problem

After reading n-1 characters, the following characters are still stored in the buffer. If the buffer is not cleaned, the characters left in the buffer will be read next time!

code

#include <stdio.h>
#define MAX 10
int main (void)
{
    char p[MAX];
    printf("Please enter a string:");
    fgets(p, MAX, stdin);  /*MAX-1 characters actually read*/
    
    fputs(p, stdout);  /*Do not add line breaks automatically*/
    puts(p);  /*Add line breaks automatically*/
    return 0;
}
12
123
1234
12345

problem

The fgets() function reads the newline character, so how to delete the newline character stored in the string?

  • Iterates through the string until a newline or empty character is encountered.
    • Line breaks: replace with empty characters
    • Empty character: discards the remainder of the input line

code

/*Delete the newline character read by the fgets() function*/
#include <stdio.h>
#define MAX 10
int main (void)
{
    char words[MAX];
    int i;
    printf("Enter strings(Empty line to quit): ");

    while (fgets(words, MAX, stdin) != NULL && words[0] != '\n')
    {
        i = 0;
        while (words[i] != '\n' && words[i] != '\0')
            i++;

        if (words[i] == '\n')  /*Replace the \ n symbol with an empty character*/
        {
            printf("The first%d Times, encountering line breaks...\n", i);
            words[i] = '\0';
        }
        else  /*If null characters are encountered, the remaining characters in the input line are discarded*/
        {
            printf("The first%d Times, encounter with empty character...\n", i);
            while (getchar() != '\n')  /*The read character is \ 0, the identifier of the end of the string. After reading, clear the buffer character data*/
                continue;
        }
        puts(words);  /*Finally, output the read string*/
    }

    return 0;
}

11.2.3 gets_s() function

The special fgets() function can only read data from standard input (stdin) without the third parameter

  • Discard newline
  • When reading the maximum number of characters
    • Set the first character in the target array to null
    • Reads and discards subsequent characters - > newline or end of file, then returns a null pointer
    • Call handler

11.3 string output function

11.3.1 puts() function

  • Add line breaks automatically
  • Stop output when null character is encountered
  • Empty characters must be guaranteed. The character array cannot be output normally (does not end with \ 0)
  • The parameter is char * int

The gets() function discards the newline character

code

char mesg [] = "Everything is ok!";
puts(mesg + 3);  /*Note that the starting position at this time is to print from r*/
puts(&mesg[3]); /*The effect is the same as above. Note that the parameter type passed is pointer*/

result

rything is ok!
rything is ok!
===Isn't it a little incredible?===

11.3.2 fputs() function

  • Parameter 2: indicates the file to write data to
  • Line breaks are not added

The fgets() function preserves line breaks

11.3.3 user defined output function

code

/*Custom print function 1*/
void putx1(const char * words)  /*The string to be printed cannot be changed*/
{
   while (*words != '\0')  /* while (*words)Can be used as a condition */
       putchar(*words++);  /*Typical application of pointer type*/
}

/*Custom print function 2*/
void putx2(const char strings[])
{
    int i = 0;
    while (strings[i] != '\0')
        putchar(strings[i++]);  /*Array type*/

}

11.4 string function

11.4.1 strcat() function

Function: splice strings and attach the backup of the second string to the end of the first string!

Question: will the null character \ 0 at the end of the first string be overwritten?

  • The first character changes
  • The second character does not change

Disadvantages: it is impossible to determine whether the first array has enough capacity. Similar to the gets() function, it will lead to serious consequences, buffer overflow!!!

11.4.2 strncat() function

  • strncat(first, second, 10)
    • Splice the first 10 characters of the second parameter after the first character
    • Stop when nth character or null character is encountered

code

#include <stdio.h>
#include <string.h>

int main (void)
{
    char first[100] = "carter ";
    char * second = "Sympathize Aristo far-off regions-Liao";
    strncat(first, second, 8);
    puts(first);
    puts(second);
    return 0;
}

result

carter Aristo
Min Aristo ends of the world - Liao

11.4.3 strcmp() function

strcmp(A, B)

  • Return value: difference between ASCII codes of A - B
  • Strings are compared instead of characters

Non zero is true

  • Same: 0
  • Different: not 0

Disadvantages: compare two strings from beginning to end

Question: how to deal with when only comparing whether the prefixes of two words are the same?

code

#include <stdio.h>
#include <string.h>
#define ANSWER "hello"
const int SIZE = 6;

int main (void)
{
    char try[SIZE];

    printf("Enter a word: ");
    scanf("%s", try);  /*The character array name represents the address of the first element*/

    printf("value01 = %d\n", try == ANSWER);  /*At this time, the comparison is whether the two addresses are the same*/

    /*strcmp()Function. At this time, the contents of two strings are compared, the same: 0, different: 1*/
    printf("value02 = %d\n", strcmp(try, ANSWER));
    
    /*=====!Wrong understanding=====*/
    /*Compare whether the contents pointed to by the two addresses are consistent. The same: 1(true) but different: 0(false)*/
    printf("\n%#p\n%#p\nvalue03 = %d",*try, *ANSWER, *try == *ANSWER);
    return 0;
}

demonstration

value01 = 0 different
Value02 = 0 same as StrCmp

! Wrong understanding!

0X0000000000000068
0X0000000000000068
value03 = 1, pointing to the same address element

11.4.4 strncmp() function

Advantages: you can compare the different parts of two strings, and you can also compare the characters in the specified position

Knowledge development: #The difference between define and const (reference link)

code

#include <stdio.h>
#include <string.h>
#define MAX 6 / * correct declaration: indicates a constant precompile: the processing constant before compilation*/
//const int MAX = 6;  /* Error: Int type variable, initialized as a constant! Variable sized object may not be initialized can use variable length array, but variables cannot be initialized*/


int main (void)
{
    const char *words[MAX] =
    {
        "aristoxxx01", "aristoxxx02",
        "filename", "teleScope",
        "aristoCritic", "glove"
    };

    int count = 0;
    for (int i = 0; i < MAX; i++)
        if (strncmp("aristo", words[i], 6) == 0)
        {
            printf("Found: %s\n", words[i]);
            count++;
        }
    printf("The list contained %d words beginning"
            " with aristo.\n", count);

    return 0;
}

demonstration

Found: aristoxxx01
Found: aristoxxx02
Found: aristoCritic
The list contained 3 words beginning with aristo.

11.4.5 strcpy() function

performance

  • ptr2 = ptr1 address copy
  • strcpy() function string copy
  • The following character overwrites the previous character (the position of the first character can be changed)
  • The first argument does not have to point to the beginning of the array

shortcoming

  • Unable to determine whether the target character array can hold, buffer overflow!!!
  • unsafe

code

char * ps;
const char * orig = "beast";
char copy[SIZE] = "Be the best that you can be.";

ps  = strcpy(copy + 7, orig);  /*ps Return value: after the 8th element in copy*/
puts(copy);
puts(orig);
puts(ps);

result

Be the beast  ===Use all the following beast Cover up===
beast   ===Source characters to be copied===
beast  ===copy Character after the 8th element===

syntax error

char target[10];
target = "carter";  /*Syntax error, compilation failed*/
puts(target);

11.4.6 strncpy() function

strncpy(A, B, n)

  • Copy B to A
  • A is the target string
  • B is the source string
  • Copy up to n characters
    • When the number of B characters < n: the target string A can carry the empty character of B
    • When the number of B characters > n: the target string A does not necessarily contain empty characters, so A[MAX - 1] = '\ 0' is required to ensure that A is A string

11.4.7 sprintf() function

Declared in stdio H, the data can be written into the string, and multiple elements can be combined into a string, which is equivalent to the formatting of the string

String combination function

char formal[100];  /*Target string declaration*/
char firstName[20] = "Liao";
char lastName[20] = "Shu Xing";
double price = 379.99;

sprintf(formal, "%s, %-4s, $%6.2f", lastName, firstName, price);  /*String combination function*/
puts(formal);  /*Output the combined string*/

result

Shu Xing, Liao, $379.99

11.5 command line parameters

  • All read from the command line are strings
  • atoi() function: convert string to int type

code

/*Command line parameters*/
#include <stdio.h>

int main (int argc, char * argv[])
{
    printf("Number of strings on the command line:%d\n", argc);
    printf("Parameter values on the command line:\n");
    
    for (int i = 0; i < argc; i++)
        printf("\targv[%d] = %s\n", i, argv[i]);

    return 0;
}

=====be careful=====
	Generally, the number of strings needs to be determined.
	For example: if(argc < 2) return -1;

result

PS D:\FileDir\Java\VSCode\CLanguage\Chapter-11> .\command_line_argument 11 12 "hello" world "this is my gloves"
Number of strings in the command line: 6
 Parameter values on the command line:
        argv[0] = D:\FileDir\Java\VSCode\CLanguage\Chapter-11\command_line_argument.exe
        argv[1] = 11
        argv[2] = 12
        argv[3] = hello
        argv[4] = world
        argv[5] = this is my gloves

11.6 ctype.h character functions and strings

code

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void ToUpper (char * str);

int main (void)
{
    char strings[] = "carter no\nhello\nworld\n";
    char * find;
    find = strchr(strings, '\n');  //Find the first line break
    if (find)  // If the address is not NULL
        *find = '\0';  //String end symbol
    ToUpper(strings);
    puts(strings);
    return 0;
}

/**
 * @brief Capitalize all characters in the string
 * 
 * @param str String pointer
 */
void ToUpper (char * str)
{
    while (*str)
    {
        *str = toupper(*str);  // Can only act on a single character
        str++;
    }
}

demonstration

CARTER NO

Chapter 12 storage category, link and memory management

12.1 storage category

5 storage categories

Storage categoryStorage periodScopelinkDeclaration method
automaticautomaticblocknothingIn block
registerautomaticblocknothingWithin the block, use the keyword register
Static external linkstatic statefileexternalOutside all functions
Static internal linkstatic statefileinsideExcept for all functions, use the keyword static
Static no linkstatic stateblocknothingWithin the block, use the keyword static

12.1.1 scope

  1. Block scope: a code area enclosed in curly braces
  2. Function scope: only used for the label of goto statement
  3. Function prototype scope: at parameter definition = = = > end of prototype declaration
  4. File scope: the variable is defined outside the function

File scope variable: also known as global variable

12.1.2 links

  1. External links: file scope variables (global variables)
  2. Internal link: static file scope variable (static global variable)
  3. No link: variables of block scope, function scope and function prototype scope

Translation unit: a source code file and the header file it contains

12.1.3 storage period

  1. Static storage cycle: it always exists during program execution. All file scope variables are decorated with static storage cycle and static keyword
  2. Thread storage cycle: used for concurrent programming, keywords_ Thread_local
  3. Automatic storage cycle: block scope
  4. Dynamically allocate storage cycle: variable length array

12.1.4 static variables of block scope

  • Initialize only once
  • Address unchanged
  • Content change

code

#include <stdio.h>

int main (void)
{
    for(int i = 1; i <= 10; i++)
    {
        static int total = 0;  /*For static, unlinked, block scoped variables, if the static variables are not initialized, they will be automatically initialized to 0 and only initialized once*/
        total += i;
        printf("The first%d second, total = %d\n", i, total);
    }
    return 0;
}

result

The first time, total = 1
Second time, total = 3
Third time, total = 6
The 4th time, total = 10
The 5th time, total = 15
The 6th time, total = 21
The 7th time, total = 28
8th time, total = 36
The 9th time, total = 45
10th time, total = 55

12.1.4 static variables of external links

Keywords: extern

  • Reference an existing external definition
  • No memory allocated

tools.h

/*Static file scope*/
static int externalNumber = 9;

controller.c

#include <stdio.h>
#The header file of include "tools. H" / * externalnumber. Double quotation marks indicate that the included file is located in the current directory*/

/*Static variables of external links must be declared in this way*/
extern int externalNumber;

int main (void){
    printf("externalNumber = %d", ++externalNumber);
    return 0;
}

result

externalNumber = 10

12.2 random number functions and static variables

ANSI C library provides rand() function to generate random number - pseudo-random number generator. Run the same code twice to get the same random number

Solution: use the time() function to reset the seed

12.3 allocate memory malloc() and free() functions

malloc() function

  • Pointer receiving
  • Use with free()
  • The prototype is in stdlib H header file
  • If the allocation fails, return the NULL pointer and call the exit() function to exit the program
    • EXIT_FAILURE
    • EXIT_SUCCESS (equivalent to 0), the program ends normally

free() function

  • The amount of memory used by automatic variables automatically increases or decreases during program execution
  • The amount of dynamically allocated memory will only increase unless freed using free()
  • Not using free() will lead to memory leak and memory exhaustion!!!

Three methods of creating arrays

  • Declaration array - constant expression
  • Declare variable length arrays (a new feature of C99) - variable expressions represent the dimensions of the array
  • Declare a pointer - call the malloc() function and assign its return value to the pointer

12.4 storage category and dynamic memory allocation

  • Static storage category
    • Amount of memory: determined at compile time
    • Creating: program execution
    • Destroy: at the end of the program
  • Automatic storage category
    • Amount of memory: increases and decreases with program calls
    • Create: when entering the block
    • Destroy: when leaving the block
    • This part of memory is usually treated as a stack (last in, first out)
  • Dynamically allocated memory
    • Create: when calling malloc() function
    • Destroy: when calling the free() function
    • In general, dynamic memory is slower than stack memory!

12.5 const qualifier

  • const float * pf value unchanged
  • float * const pf pointer pointing unchanged
  • float const * pf value unchanged
  • The value of float * const + pf remains unchanged

Summary: left value and right pointer remain unchanged

Chapter 13 document input / output

13.1 document mode

  • Text content

  • Binary content

  • Text file format

  • Binary file format

C provides two ways to access files

  • Text mode: the content seen by the program is different from that of the file. It will map the end of the line or the end of the file represented by the local environment to C mode
  • Binary mode: the program can access every byte of the file without mapping

13.2 I/O level

  • Low level I/O: use the basic I/O services provided by the operating system. (may only be applicable to the specified system)
  • Standard high-level I/O uses the standard package of C library and stdio H header file definition. (highly portable)

13.3 introduction to I / O function

13.3.1 return() and exit() functions

  • exit() will still terminate the program
  • return will only give control to the upper level of recursion until the first level

13.3.2 fopen() function

Fopen (file name, open mode)

  • The following are all open files in file mode
Pattern stringmeaning
"r"Read mode
"w"Write mode; Clear the text content and create it if it does not exist
"a"Write mode; The tail is newly added. If it does not exist, it will be created
"r+"Update mode; Read write file
"w+"Update mode; Read and write the file, clear the text content, and create it if it does not exist
"a+"Update mode; Read / write file, add at the end of the file, and create it if it does not exist

13.3.3 fprintf() and fscanf() functions

code

fprintf(stdout, "Do one's best level");  /*standard output */
printf("Do one's best level");  /*The function is the same as above*/

int i;
fscanf(stdin, "%d", &i);  /*stdin Standard input*/
scanf("%d", &i);  /*ditto*/


rewind(fp);  /*Go back to the beginning of the file*/
fscanf(fp, "%s", words) == 1;  /*Scan text content, scan words (without spaces)*/

13.3.4 fgets() and fputs() functions

  • Fgets (character array, string size, file pointer): keep line breaks
  • Fputs (character array, file pointer): do not add line breaks

13.3.5 fseek() and ftell() functions

fseek() function

  • Move directly to any byte in the file opened by fopen()

Example: fseek(file, 0L, SEEK_SET) - > locate to the beginning of the file

patternStart point of offset
SEEK_SETFile start
SEEK_CURcurrent location
SEEK_ENDend of file

ftell() function

  • Returns a value of type long (which limits the character size of the file), indicating the current position in the file
function calleffect
fseek(file, 0L, SEEK_SET)Navigate to the beginning of the file
fseek(file, 0L, SEEK_CUR)Hold current position
fseek(file, 0L, SEEK_END)Navigate to the end of the file
fseek(file, ftell-pos, SEEK_SET)To the location of fTell pos from the beginning of the file. FTell POS is the return value of ftell()

Hidden problems

The return value type of long type leads to limited data size and is not suitable for the era of big data.

13.3.6 fgetpos() and fsetpos() functions

New type fpos_t (for file position type)

fpos_t is not a basic data type

Function prototype

  • int fgetpos (FILE * restrict, fpos_t * restrict pos);
  • int fsetpos(FILE *stream, const fpost_t *pos)

13.4 other standard I/O functions

13.4.1 ungetc() function

Function: put the specified characters back into the input stream. ANSI C standard ensures that only one character is put back at a time.

Parameter: int ungetc (int c, file * FP)

13.4.2 fflush() function

Function: refresh the buffer for updating the stream (any read-write mode)

Parameter: int fflush(FILE *fp)

13.4.3 fread() and fwrite() functions

Q: how to save numerical data in a file?

A: use fprintf() to convert numeric values into strings

double num = 1. / 3.;
fprintf(fp, "%f", num);

Disadvantages: changing the conversion description will change the amount of space required to store the value, and will also lead to different values! And cannot be restored to higher accuracy!

Q: how to ensure the consistency of values before and after storage?

A: the most accurate way is to use the same bit combination as the computer to store.

Solution: therefore, the value of double type should be stored in a double size unit.

If the data is stored in a file in the representation used by the program, it is called storing data in binary form. There is no conversion process from numeric form - > string

For standard I/O, the fread() and fwrite functions are used to process data in binary form.

fwrite() function prototype

Function: write binary numbers to files

Parameter: size_t fwrite (const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict fp);

Case: fwrite(buffer, 256, 2, fp)

Write two 256 byte data from buff to file fp and return the written character size.

Prototype of fread() function

Function: read file contents

Parameter: size_t fread(void * restrict ptr, size_t size, size_t nmeb, FILE * fp);

Case: FREAD (early, sizeof (double), 10 FP);

Copy 10 double size values into the discoveries array.

Chapter 14 structure and other data forms

14.1 structure statement / definition

example

struct book {
    char title [MAXTITLE];
    float value;
};

The compiler is not asked to allocate space at this time

14.1.1 access structure members

Structure member operator -- point (.) Members of access structure

&book. Value: the priority of the point is greater than&

example

/*Initialization mode of structure*/
#include <stdio.H>
#define MAXTITLE 41

/*book Structure declaration*/
struct book {
    char title[MAXTITLE];
    float value;

};

int main (void)
{
    struct book gift = {.value = 11.99, .title = "Swing", 11.98, 11.90}; /*11.90 Where have you been?*/
    printf("title = %s  value= %f", gift.title, gift.value);
    return 0;
}

warning ⚠

structInitializer.c:14:66: warning: excess elements in struct initializer //Element overflow
    struct book gift = {.value = 11.99, .title = "Swing", 11.98, 11.90};
                                                                  ^~~~~
structInitializer.c:14:66: note: (near initialization for 'gift')
title = Swing  value= 11.980000

14.1.2 identify members of structure array

/*Structure array*/
#include <stdio.h>
#define MAXTITLE 41
const int MAX = 5;

struct book {
    char title [MAXTITLE];
    float value;
};

int main (void)
{
    struct book libry[MAX];
    libry;                  // An array of book structures
    libry[2];               // The third array element is the book structure
    libry[2].title;         // A char character array, the member title in Library [2]
    libry[2].title[4];      // A char character
    return 0;
}

14.2 pointer of pointer structure

14.2.1 pointer advantages

  1. Pointers to pointer structures are easier to manipulate than the structure itself
  2. In the early C language, structure cannot be passed to function as parameter, but pointer of pointer structure can be passed
  3. It is usually more efficient to pass pointers
  4. Some structures used to represent data contain pointers to other structures

14.2.2 pointer access structure members

  • Method 1: him - > value;
  • Mode 2: (* him) value;
struct book *it;
it -> value;  // With & Library [0] value == (*it).value
it++;  // Characteristics of pointer

14.3 structural characteristics

Note: it is allowed to assign a structure to another structure, but the array cannot be assigned to another structure

Q: How do arrays assign values to each other?

A: Wrap array with structure!!!

14.3.1 structure parameters

statement

struct book getInfo(struct book);  // Return: book type structure; Formal parameter: book type structure

14.3.2 selection of structure and structure pointer

Pointer

  • advantage
    • efficient
    • universality
  • shortcoming
    • Unable to protect data - const qualifier (ANSI C)

Structure itself

  • advantage
    • It processes a copy of the original data and protects the original data
    • Clearer code style
  • shortcoming
    • The old version can only pass pointers
    • Waste of time & storage space

14.3.3 character array and character pointer in structure

There are two forms of string storage declaration:

① Character array

② Character pointer

#define LEN 20
struct names {  // ① Character array (simple)
    char first[LEN];
    char last[LEN];
};

struct pnames {  // ② Character pointer, abuse can lead to serious consequences
    char * first;
    char * last;
};

int main (void)
{
    struct pnames ptr;
    char temp[LEN];
    ptr -> first = (char *)malloc (strlen(temp) + 1);  // malloc function for memory allocation
    
    free(ptr -> first);  // Free memory resources
    return 0;
}

14.4 scalable array (C99)

14.4.1 declare rules with scalable array structure

  • The telescopic array member must be the last member of the structure
  • There must be at least one member in the structure
  • The declaration of a telescopic array is similar to that of an ordinary array, except that it is empty in square brackets
struct flex
{
    int count;
    double average;
    double scores[];  // Scalable array member
};

struct plex *pf; // ① Declare a pointer to a pointer structure

pf = malloc(sizeof(struct flex) + 5 * sizeof(double));  // ② Please allocate storage space for a structure and an array
pf->count = 5;
pf->scores[2] = 18.2;  // have access to

14.4.2 provisions on members of scalable array

Structure with telescopic array

  1. You cannot assign and copy with structures (only members other than telescopic arrays can be copied)
  2. A structure with a scalable array cannot become a member of another person or an array member
  3. Make parameters: do not pass the structure, but the address

14.5 Union

14.5.1 joint statement

union hold {
    int digit;
    double bigfl;
    char letter;
};  // Consistent with the declaration of structure

14.5.2 joint and structural differences

If 14.5.1 declares a structure, it can store an int type, a double type and a char type

Union: only one can be stored, either an int, or a double or char

In the union of 14.5.1, declaring a hold Union will allocate only one memory space of double data (8 bytes)

The previous assignment statement will be overwritten later

Joint naming

struct data {
    char make[15];
    int status;
    union {
        struct owner ow;
        int x;
    };
}

14.6 enumeration types

The purpose of enumerating types is to improve the readability and maintainability of programs

The enumeration type is an integer type

/*Enumeration type tester*/
#include <stdio.h>
enum spectrum {red, orange, yellow, green, blue, violet};  /*The enumeration type is an integer type*/

int main (void)
{
    enum spectrum color;
    color = blue;
    if (color == blue)
        puts("It is blue...");
    for (color = red; color <= violet; color++)  /*C Language can use + +, but C + + does not allow it*/
        printf("%d\n", color);  /*Enumeration type is integer type% d received*/
        
    return 0;
}

demonstration

It is blue...
0
1
2
3
4
5

Enumeration types can specify integer values

enum levels {cat, dog = 10, cow, rat, horse}; /*Note that cat == 0, dog, cow, rat == 10, 11, 12*/

14.7 typedef introduction

14.7.1 difference between typedef and #define

typedef: a custom name for a type (which cannot be a value), usually uppercase

typedef

char * STRING;  // No typedef: the compiler recognizes STRING as a pointer variable to char

typedef char * STRING; // With typedef: the compiler interprets STRING as an identifier of a type that points to a pointer to char

STRING name, sign;
// Note: equivalent to:
char * name, * sign;

#define

#define STRING char *
STRING name, sign;
// Note: equivalent to
char * name, sign;

#define bool _Bool
#define true 1
#define false 0

14.7.2 typedef modification structure

/*tyoedef structure of modification*/
#include <stdio.h>

typedef struct {
    int x;
    int y;
} rect;

int main (void)
{
    rect r1 = {3, 4};
    printf("r1.x = %d, r1.y = %d\n", r1.x, r1.y);

    rect r2;
    printf("r2.x = %d, r2.y = %d\n", r2.x, r2.y);

    r2 = r1;
    printf("r2.x = %d, r2.y = %d\n", r2.x, r2.y);
    return 0;
}

demonstration

r1.x = 3, r1.y = 4
r2.x = 1643472, r2.y = 0
r2.x = 3, r2.y = 4

be careful

rect r1 = {3, 4};
rect r2;
// Can be translated as:
struct {int x; int y;} r1 = {3, 4};
struct {int x; int y;} r2;

14.8 other complicated statements

Table 14.1 symbols that can be used in declaration

Symbolmeaning
*Represents a pointer
()Represents a function
[]Represents an array

Here are some complex statements:

/* 
[]Is the sign that associative law has priority over * 
First pointer -- > is a pointer
 First, the array -- > is an array
*/

int board[8][8];		// Declare an array containing an int array

int ** ptr;				// Declare a pointer to a pointer, and the pointer pointed to points to int

int * reisks[8];		//  Declare an array containing 8 elements. Each element is a pointer to int - pointer array

int (* resks)[8];		// Declare a pointer to the array, which contains 8 int type data --- pointers to the array

int * off[3][4];		// Declare an array containing 3x4 elements, and each array is a pointer to int

int (* uff)[3][4];		// Declare a pointer to an array containing 3x4 int type data

int (* uof[3])[4];		// Declare an array containing 3 pointer elements, and each pointer points to an array containing 4 int type elements

14.9 pointer to function

void (*pf) (char *);  // pf is a pointer to the function, the parameter list is (char *), and the return value is void
void *pf (char *);  // pf is a function that returns a character pointer

void ToUpper(char *);
pf = ToUpper;  // allow

Page415

Warning: this document is only for personal learning!!!

Topics: C