An overview of the
C language is very necessary for Android development, no matter you are to read the source code, or want to learn the NDK, audio and video, performance optimization, etc., inevitably need to contact to C, and C language belong to the system level, the operating system kernel has the figure of the C, so I today to learn C language, this blog as a note, In case you forget later
Introduction to the C
C language is initially suitable for system development work, especially the program composed of the operating system. Because the running speed of the code generated by C language is almost the same as the running speed of the code compiled by assembly, C language is adopted as the system development language. Here are several examples of using C
- The operating system
- Text editor
- The printer
- Network drives and so on
C Environment Settings
The code written in the source file, which we humans can understand, needs to be compiled and translated into machine language, so that the CPU can execute the program according to instructions, and C can compile the source code into machine language through the GUN compiler
You can download Xcode directly on Mac and use the GUN compiler. Development tools can use CLion or use the text compiler
Let’s start with a HelloWord
#include <stdio.h>
int main(a)
{
/* My first C program */
printf("The first C program Hello, World! \n");
return 0;
}
Copy the code
A C program consists of
- Preprocessor instruction: The first line of a program
#include <stdio.h>
Is a preprocessor instruction that tells the C compiler to include it before actually compilingstdio.h
file - Function: next line
int main()
Is the main function, where the program starts,printf()
Is another function available in the program to display on the screenHello, World!
- variable
- Statement & expression
- /*… */ This is a comment
return 0;
Marks the end of this function and returns 0
Compile and execute the C program
- First open a text editor to add the code above
- Save the file as hello.c
- Open the command line and go to the file folder
- Type GCC hello.c to compile the code
- If there are no errors, the folder generates an executable for A.out
- Command line type a.out to run the program
- And then you can see it on the screen
Hello, World!
Last login: Mon Feb 17 14:53:00 on ttys002
L-96FCG8WP- 1504.:~ renxiaohui$ cd Desktop/
L-96FCG8WP- 1504.:Desktop renxiaohui$ cd c/
L-96FCG8WP- 1504.:c renxiaohui$ gcc hello.c
L-96FCG8WP- 1504.:c renxiaohui$a.out L-96FCG8WP- 1504.:c renxiaohui$
Copy the code
Introduction to C language
1 Basic Syntax
identifier
A marker is A variable, function, or any user-defined variable name. An identifier begins with the letters A-Z, A-Z, or _ underscore, followed by zero or more letters, numbers, and underscores
No punctuation characters are allowed in identifiers, such as @%, and identifiers are case sensitive
The keyword
These keywords cannot be used as constant or variable names or other identifiers
The keyword | instructions |
---|---|
continue | End the current loop and start the next loop |
switch | Used for switch statements |
case | Switch statement branching |
default | Switch other branches in the statement |
break | Out of the current loop |
do | The body of a loop statement |
while | Loop conditions for loop statements |
if | Conditional statements |
else | The conditional statement negates the use of branches with if |
for | A loop statement |
goto | Unconditional jump statement |
return | Subroutine return statement, with or without arguments |
char | Declare a character variable or return value type |
double | Declares the return value type of a double-precision floating-point object or function |
float | Declare a floating point variable or return value type |
short | Declare a short integer variable or return value type |
int | Declare an integer variable or return value type |
long | Declares a long integer variable or return value type |
unsigned | Declare an unsigned type variable or return value type |
void | Declare a function with no return value or argument, and declare no type pointer |
enum | Declaring enumeration types |
static | Declare static variables |
auto | Automatic declaration of variables |
const | Defines constants. If a variable is decorated with const, its value cannot be changed |
extern | Declare variables or functions defined in other files or elsewhere in this file |
register | Declare register variables |
signed | Declare a variable of signed type |
sizeof | Calculates the length of a data type or variable |
struct | Declare the structure type |
union | Declared common body |
typedef | Alias the data type |
volatile | Describes how variables can change implicitly during execution |
You can see that 70% is in Java, so it’s not that hard to learn
2 Data Types
The data types in C can be classified as follows
type | describe |
---|---|
Basic data types | They are arithmetic types and contain two types, integer types and floating point types |
Enumerated type | They are also arithmetic types and are used to define discrete integer value variables that can only be assigned certain values in a program |
void | Indicates that no value is available |
The derived type | This includes pointer types, array types, structure types, common body types, and function types |
Let’s start with the basic data types
Integer types
type | Storage size | Range of values |
---|---|---|
char | 1 byte | Or a scale of 0-255-128-127 |
unsigned char | 1 byte | 0-255. |
signed char | 1 byte | – 128-127 |
int | 2 or 4 bytes | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
unsigned int | 2 or 4 bytes | 0 to 65,535 or 0 to 4,294,967,295 |
short | 2 – | 32768 to 32767 |
unsigned short | 2 – | 0 到 65,535 |
long | 4 bytes | 2147483648 to 2147483647 |
unsigned long | 4 bytes | 0 to 4294967295 |
The storage sizeof each type, relative to the system bits, can be calculated using sizeof to get the exact size
#include <stdio.h>
#include <limits.h>
int main(a){
printf("Int storage size: %lu \n".sizeof(int));
return 0 ;
}
Copy the code
Int Storage size: 4Copy the code
Floating point types
type | Storage size | Range of values | precision |
---|---|---|---|
float | 4 bytes | 1.2 e-38 to 3.4 e | 6 decimal places |
double | 8 bytes | E+308 e-308 2.3 to 1.7 | 15 decimal places |
long double | 16 bytes | E+4932 e-4932 3.4 to 1.1 | 19 the decimal |
Void type
type | describe |
---|---|
The function returns null | There are various functions in C that do not return a value, or you could say that they return nothing. A function that does not return a value has a null return type. For example, void exit (int status); |
Function argument is null | There are various functions in C that don’t take any arguments. A function that takes no arguments can accept a void. For example, int rand (void); |
Pointer to void | Pointers of type void* represent the address of the object, not the type, for example, the memory allocation function void* malloc(size_t size); Returns a pointer to void, which can be converted to any data type. |
Three variables
Variables are the names of the storage areas that can be manipulated by the program. In C, each variable has a specific type, which determines the size and layout of the variable. Values within this range can be stored in memory
C language has basic data type variables, but also can have other types of variables, such as arrays, Pointers, enumerations, structures, common, and so on
Definition of variables
A variable definition tells the packet where and how to create a store for a variable. A variable definition specifies a data type and contains a list of one or more variables of that type
type variable_list;
Copy the code
Type must be a valid C data type, and variable_list is the name of the variable, which can be multiple
int i, j, k;
char c, ch;
float f, salary;
double d;
Copy the code
I,j,k above declare and define variables I,j,k
Variables can be initialized at declaration time
type variable_name = value; For example,extern int d = 3, f = 5; // declaration and initialization of d and f
int d = 3, f = 5; // Define and initialize d and f
byte z = 22; // Define and initialize z
char x = 'x';
Copy the code
Declaration of variables in C
The declaration of a variable, like the editor, ensures that the variable exists with the specified type and name, so that the editor can compile further without knowing the full details of the variable
There are two cases of variable declarations
- Int a has already created storage space when it is declared.
- Extern int a extern int A, where a variable can be defined in another file. Extern int A; / / extern int A; / / extern int A; / / extern int A
- Except for the extern keyword, everything else is a variable definition
extern int i; // Declaration, not definition
int i; // Declaration is also a definition
Copy the code
4 constants
Constants are fixed values that do not change during the course of a program. These fixed values are also called literals
Constants can be any basic data type and are not modified after a value is defined
Define constants
There are two ways of defining constants in C
- use
#define
The preprocessor
#define identifier value
#include <stdio.h>
#include <limits.h>
#define FFF 10
#define DDD 20
#define HHH '\n'
int main(a){
int a ;
a =FFF*DDD;
printf("Value, % d",a);
printf("\n string %c",HHH);
return 0 ;
}
Copy the code
Value,200String,Copy the code
- use
const
The keyword
const type variable = value;
int main(a) {
const int FFF =10;
const int DDD=20;
const char HHH='\n';
int a;
a = FFF * DDD;
printf("Value, % d", a);
printf("\n string %c", HHH);
return 0;
}
Copy the code
Value,200String,Copy the code
5 storage class
Storage classes define the scope and life cycle of variables, functions, and functions in C. These specifiers precede the types they modify. The available storage classes are listed below
- auto
- register
- static
- extern
Auto storage class
The Auto store class is the default store class for all local variables
{
int mount;
auto int month;
}
Copy the code
Both of these are the same, auto can only be used in functions, that is, only to modify local variables
register
Used to define local variables that are stored in registers rather than RAM, meaning that the maximum size of a variable is the size of the register
{
register int miles;
}
Copy the code
Registers are used only for variables that need quick access, such as counters
static
The compiler holds the value of a local variable for the duration of the declaration cycle, rather than creating and destroying it each time it enters and leaves the scope, so using static to modify a local variable can hold the value of a local variable between function calls
Static can also be used with a global variable. When static modifies a global variable, the scope of the variable is restricted to its own file. (A normal global variable can be accessed by any file after being declared extern)
Static functions: Same as global variables above (non-static functions can be referenced directly in another file, even without extern declaration)
extern
Used to provide a reference to a global variable visible to all program files
Extern = extern; extern = extern; extern = extern; extern = extern; extern = extern; extern = extern
First file
#include <stdio.h>
int count =5;
extern void add(a);
int main(a) {
add();
return 0;
}
Copy the code
Second file
#include <stdio.h>
extern int count;
void add(a){
printf("count=%d\n",count);
}
Copy the code
After the operation
bogon:untitled renxiaohui$ gcc text.c tex1.c
bogon:untitled renxiaohui$ a.out
count=5
Copy the code
6 operators
Same as Java, not record
7 judgment
With Java
8 cycles
With Java
9 function
Define a function
return_type function_name( parameter list )
{
body of the function
}
Copy the code
The components of a function
- Return value type: A function can return a value,
return_type
Is the data type of a function that returns a value, in which case some functions do not return datareturn_type
The keyword of isvoid
- Function name: The actual name of the function
function_name
- Function argument: When calling a function, you need to pass a value to the function, which can have multiple arguments or none
- Function body: The statement within a function that implements logic
int Max(int num1,int num2){
int result;
if(num1>num2){
result=num1;
}else{
result=num2;
}
return result;
}
Copy the code
This is a simple example of a function
Function declaration
The declaration of the function tells the compiler the name of the function and how to call the function, and the actual body of the function can be defined separately, right
The function declaration consists of the following parts
return_type function_name( parameter list );
Copy the code
We can declare the top function
int Max(int num1,int num2);
Copy the code
Parameter names are not important in function declarations and can be omitted
int Max(int ,int);
Copy the code
Function declaration is necessary when you define a function in one source file and call the function in another. In this case, you need to declare the function at the top of the calling function file
Call a function
#include <stdio.h>
int Max(int.int);
int main(a) {
int num1 = 100;
int num2 = 120;
int rec;
rec = Max(num1,num2);
printf("The comparison result is %d\n",rec);
return 0;
}
int Max(int num1, int num2) {
int result;
if (num1 > num2) {
result = num1;
} else {
result = num2;
}
return result;
}
Copy the code
The results for
The comparison result is120
Copy the code
10c scope rules
A local variable
Variables declared in a function block are local variables. They can only be used by the function or the function statements in the code block
#include <stdio.h>
int main (a)
{
/* Local variable declaration */
int a, b;
int c;
/* Actually initialize */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Copy the code
A,b, and c are all local variables
The global variable
Global variables are defined outside a function, usually at the top of a program, are valid for the entire life of the program, and can be accessed inside any function.
Global variables can be accessed by any function, which means that global variables are available throughout the program after being declared
A local variable and a global variable can have the same name, but within a function, if the two names are identical, the local variable is used, not the global variable
#include <stdio.h>
// Global variables
int a = 10;
int c = 40;
int main(a){
// Local variables
int a = 20;
int b =30;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
return 0;
}
Copy the code
The output
a=20
b=30
c=40
Copy the code
The difference between global and local variables
- Global variables are stored in the global storage area of memory, occupying static storage units
- Local variables are stored on the stack, and storage units for variables are dynamically allocated only when the function is called
11 array
Declare an array
type arrayName [ arraySize ];
Copy the code
ArraySize must be a constant greater than 0, type is any valid C data type, and declares a NUMS array containing 10 doubles
double nums [10];
Copy the code
Initializing an array
Initialize a fixed number of arrays
int nums [3] = {10.2.3}
Copy the code
Initialize an array of unfixed numbers
int nums []={1.2.3.4.5}
Copy the code
Assign to an array
nums[3] = 6;
Copy the code
Accessing an array element
int a = num[3];
Copy the code
The instance
#include <stdio.h>
int main(a){
int n[10];
int i,j;
for(i=0; i<10; i++){ n[i]=i*10;
}
for (int j = 0; j < 10; ++j) {
printf("%d = %d\n",j,n[j]); }}Copy the code
The results of
0 = 0
1 = 10
2 = 20
3 = 30
4 = 40
5 = 50
6 = 60
7 = 70
8 = 80
9 = 90
Copy the code
12 the enumeration
Enumeration is a basic data type in C language
enum  The enumeration name & emsp; {enumerate elements1, enumeration element2And... };Copy the code
Let’s say we define seven days a week, let’s say instead of enumerating, we use constants
#define MON 1
#define TUE 2
#define WED 3
#define THU 4
#define FRI 5
#define SAT 6
#define SUN 7
Copy the code
If we use enumeration
enum Day{
MON=1, TUE, WED, THU, FRI, SAT, SUN
}
Copy the code
This will look pretty neat
Note: By default, the first member variable is 0, followed by 1, followed by 2 if the first is 1, and so on
Enumeration variable definition
1 Define the enumeration type before defining the variable
enum DAY{
MON=1, TUE, WED, THU, FRI, SAT, SUN
};
enum DAY day;
Copy the code
Define enumeration variables as well as enumeration types
enum DAY
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;
Copy the code
3 Omit enumeration names and define enumeration variables directly
enum
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;
Copy the code
The instance
#include <stdio.h>
enum DAY {
MON = 1, TUE, WED, THU, FRI, SAT, SUN
};
int main(a) {
enum DAY day;
day=THU;
printf("enun= %d\n",day);
return 0;
}
Copy the code
The results of
enun= 4
Copy the code
In C, enumerations are treated as ints or unsigned ints, so there is no way to iterate over enumerations according to the C specification
Enumeration is used in switch
#include <stdio.h>
#include <stdlib.h>
enum Color {
red=1, green, blue
};
int main(a) {
enum Color enumColor;
printf("Please choose your favorite color (1 red, 2 green, 3 blue)");
scanf("%d",&enumColor);
switch (enumColor){
case red:
printf("You like red \n");
break;
case green:
printf("You like green \n");
break;
case blue:
printf("You like blue \n");
break;
}
return 0;
}
Copy the code
The results of
Please choose your favorite color (1red2green3Blue)1You like redCopy the code
13 a pointer
Each variable has a memory location, and each memory location defines an address that can be accessed using the ampersand symbol, which represents an address in memory
#include <stdio.h>
int main(a){
int a ;
int b[10];
printf("Memory address of a =%p\n",&a);
printf("Memory address of B =%p\n",&b);
return 0;
}
Copy the code
The results of
The memory address of A =0x7ffee5e086c8B's memory address =0x7ffee5e086d0
Copy the code
What is a pointer
A pointer is a variable whose value is the memory address of another variable that needs to be declared before it can be used
type *var-name;
Copy the code
Type is the type of the pointer, which must be a valid C data type, var-name is the name of the pointer, and * is used to indicate that the variable is a pointer.
int *aa;// an integer pointer
double *bb;// a pointer of type double
Copy the code
How to use Pointers
Using Pointers frequently involves defining a pointer variable, assigning the address of the variable to the pointer, and accessing the available address in the pointer variable
#include <stdio.h>
int main(a){
int a =20;// Define an int value
int *b;// Define a pointer
b=&a;// Assign to the pointer
printf("Address value of variable =%p\n",&a);
printf("Pointer value =%p\n",b);
printf("Address value of pointer =%d\n",*b);
return 0;
}
Copy the code
The results of
The address value of the variable =0x7ffeef4356f8The value of the pointer =0x7ffeef4356f8The address value of the pointer =20
Copy the code
NULL pointer in C
It is a good practice to assign a NULL to a pointer when declaring a variable if there is no specific address to assign. Assigning a NULL to a pointer is called a NULL pointer
int main(a){
int *var = NULL;
printf("Var address =%p\n",var);
return 0;
}
Copy the code
The address of var is =0x0
Copy the code
Pointer to pointer
#include <stdio.h>
int main(a){
int a;
int *b;
int **c;
a=40;
b=&a;
c=&b;
printf("A =%d\n",a);
printf("The value of b is =%d\n",*b);
printf("C =%d\n",**c);
return 0;
}
Copy the code
The value of a is equal to theta40B is equal to theta40The value of c is equal to theta40
Copy the code
We pass an array to a function that returns an array
#include <stdio.h>
int sum(int *arr,int size);
int* getarr(a);
int main(a) {
int a[4] = {1.2.3.4};
int v = sum(a,4);
printf("sum=%d\n",v);
int *p = getarr();
for (int i = 0; i < 4; ++i) {
printf("Array = % d \ n",*(p+i));
printf("Array = % d \ n",p[i]);
}
return 0;
}
int sum(int *arr, int size) {
int sum = 0;
for (int i = 0; i < size; ++i) {
printf("i=%d\n", arr[i]);
printf("i=%d\n", *(arr+i));
sum+=arr[i];
}
return sum;
}
int * getarr(a){
static int arr[4] = {2.4.5.7};
return arr;
}
Copy the code
i=1
i=1
i=2
i=2
i=3
i=3
i=4
i=4
sum=10Array =2Array =2Array =4Array =4Array =5Array =5Array =7Array =7
Copy the code
Pointer arithmetic
++, –, +, -, etc. If PRT is an int address 1000, then PRT ++ will point to 1004 (move 4 bytes). If PRT is a char address 1000, then PRT ++ will be executed. PRT will point to 1001, which is also type dependent
- Each increment of the pointer actually points to the location of the next element
- Each time the pointer decrement, it actually points to the location of the last element
- The number of bytes a pointer jumps between incrementing and decrementing depends on the length of the data type of the variable to which the pointer points, such as int, which is 4 bytes
Incrementing a pointer
#include <stdio.h>
const int Max = 3;
int main(a) {
int arr[3] = {1.2.3};
int i ,*p;
// Assign the address of the first element in the array to the p pointer
p = arr;
for (int i = 0; i < Max; ++i) {
printf("Element address =%p\n", p);
printf("Element address =%d\n", *p);
// Move to the next position
p++;
}
return 0;
}
Copy the code
Element address =0x7ffee165b6acElement address =1Element address =0x7ffee165b6b0Element address =2Element address =0x7ffee165b6b4Element address =3
Copy the code
Pointer to an array
In one case, we can store memory address values in an array
#include <stdio.h>
const int Max= 3;
int main(a){
int arr[3] = {1.2.3};
int *p[Max];
for (int i = 0; i <Max ; ++i) {
p[i]=&arr[i];
}
for (int j = 0; j < Max; ++j) {
printf("Pointer array data =%p\n",p[j]);
printf("Pointer array data value =%d\n",*p[j]);
}
return 0;
}
Copy the code
Pointer array data =0x7ffee7cda6acPointer array data value =1Pointer array data =0x7ffee7cda6b0Pointer array data value =2Pointer array data =0x7ffee7cda6b4Pointer array data value =3
Copy the code
Pointer to pointer
Pointers can also point to Pointers
#include <stdio.h>
int main(a){
int a = 10;
int *b;
int **c;
b=&a;
c=&b;
printf("A =%d\n",a);
printf("The value of b is =%d\n",*b);
printf("C =%d\n",**c);
}
Copy the code
The value of a is equal to theta10B is equal to theta10The value of c is equal to theta10
Copy the code
Pass a pointer to a function
#include <stdio.h>
#include <time.h>
void getlong(unsigned long *a);
int main(a) {
unsigned long b;
getlong(&b);
printf("The value of b is =%ld\n",b);
}
void getlong(unsigned long *a) {
*a = time(NULL);
return;
}
Copy the code
B is equal to theta1585048748
Copy the code
Function Pointers and callback functions
A function pointer is a pointer variable that points to a function. A function pointer can pass arguments and call a function like a normal function
Function return value type (* pointer variable name) (function argument list);Copy the code
#include <stdio.h>
int max(int.int);
int main(a) {
//p is a function pointer
int (*p)(int.int) = &max;//& can be omitted
int a, b, c, d;
printf("Please enter three numbers:");
scanf("%d,%d,%d", &a, &b, &c);
d = p(p(a, b), c);// call Max (a,b),c);
printf("D =%d\n", d);
return 0;
}
int max(int a, int b) {
return a > b ? a : b;
}
Copy the code
The output
Please enter three numbers:1.2.3D is equal to theta3
Copy the code
Pass the pointer function as an argument to the function
#include <stdio.h>
#include <stdlib.h>
void setvalue(int *arr, int b, int(*p)(void)) {
for (int i = 0; i < b; ++i) {
arr[i] = p();
}
}
int stett(int(*p)(void)){
return p();
}
int getvalue(void) {
return rand();
}
int main() {
int arr[10];
setvalue(arr, 10, getvalue);
for (int i = 0; i < 10; ++i) {
printf("i=%d\n", arr[i]);
}
int b;
b= stett(getvalue);
printf("b=%d\n", b);
return 0;
}
Copy the code
The results of
i=16807
i=282475249
i=1622650073
i=984943658
i=1144108930
i=470211272
i=101027544
i=1457850878
i=1458777923
i=2007237709
b=823564440
Copy the code
15 string
C defines the string Hello in two forms, the difference between a string and an array of characters: whether the last bit is a null character
#include <stdio.h>
int main(a){
char hello[6] = {'H'.'e'.'l'.'l'.'o'.'\ 0'};
char hello1[]= "hello";
char *hello2="hello";
printf("Test = % s \ n",hello);
printf("Test = % s \ n",hello1);
printf("Test = % s \ n",hello2);
return 0;
}
Copy the code
Test =Hello test =Hello test =HelloCopy the code
16 structure
Structures can store different types of data items
Define a structure
struct tag {
member-list
member-list
member-list. } variable-list ;
Copy the code
- Tag: Indicates the structure tag
- Member-list: struct data entry
- Variable-list: structure variables
struct Book {
int book_id ;
char title[50];
char author[50];
char subject[50];
} book;
Copy the code
In general, at least two tags, member-list, and variable-list must appear. Here is an example:
// This declaration declares a structure with three members: integer A, character B, and double c
// the struct s1 variable is also declared
// This structure is not labeled
struct
{
int a;
char b;
double c;
} s1;
// This declaration declares a structure with three members: integer A, character B, and double c
// The tag of the structure is named SIMPLE, and no variables are declared
struct SIMPLE
{
int a;
char b;
double c;
};
// Add variables T1, T2, t3 to the SIMPLE tag structure
struct SIMPLE t1.t2[20], *t3;
// It is also possible to create new types using typedefs
typedef struct
{
int a;
char b;
double c;
} Simple2;
// You can now declare new structure variables using Simple2 as type
Simple2 u1, u2[20], *u3;
Copy the code
A structure can contain other structures and Pointers
// Struct contains other struct
struct AA{
int a;
struct Book b;
};
// The structure contains its own pointer
struct BB{
int b;
struct BB *nextbb
};
Copy the code
Initialization of a structure
struct Book {
int book_id ;
char title[50];
char author[50];
char subject[50];
} book= {1."C"."Xiao Ming"."bb"};
Copy the code
Title: C author: Xiaoming Subject: bb book_id:1
Copy the code
Access the members of the structure
Access structure members can be used. Symbols, such as book.title above;
int main(a){
struct Book book1;
strcpy(book1.title,"Study book");
strcpy(book1.author,"Little red");
strcpy(book1.subject,"111");
book1.book_id=222;
printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book1.title, book1.author, book1.subject, book1.book_id);
return 0;
}
Copy the code
Title: Study book author: Xiaohong Subject:111
book_id: 222
Copy the code
Struct as argument to function
void printstuct(struct Book book);
int main(a){
struct Book book1;
strcpy(book1.title,"Study book");
strcpy(book1.author,"Little red");
strcpy(book1.subject,"111");
book1.book_id=222;
printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book1.title, book1.author, book1.subject, book1.book_id);
printstuct(book1);
return 0;
}
void printstuct(struct Book book){
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
Copy the code
Title: Study book author: Xiaohong Subject:111
book_id: 222Book title Book author Book subject:111
Book book_id : 222
Copy the code
Pointer to a structure
Define, assign, call
struct Books *struct_pointer;
struct_pointer = &Book1;
struct_pointer->title;
Copy the code
int main(a) {
struct Book book1;
strcpy(book1.title, "Study book");
strcpy(book1.author, "Little red");
strcpy(book1.subject, "111");
book1.book_id = 222;
printstuct1(&book1);
return 0;
}
void printstuct1(struct Book *book) {
printf("Book title : %s\n", book->title);
printf("Book author : %s\n", book->author);
printf("Book subject : %s\n", book->subject);
printf("Book book_id : %d\n", book->book_id);
}
Copy the code
Book title Book author Book subject:111
Book book_id : 222
Copy the code
17 common body
A pool is a special data type that allows different data types to be stored in the same location. A pool can be defined with multiple members, but only one member can have a value at any time
Defining Commons
I’m going to use union to define the Commons,
union [uniontag] { member definition; member definition; . member definition; } [oneor more union variables];
Copy the code
The union tag is optional for each member definition; Are standard variable definitions, such as int I char B, etc. One or more common variables can optionally be defined before the semicolon
Defines a pool whose members are int,float,char[]
#include <stdio.h>
#include <string.h>
union Data {
int a;
char b[100];
float c;
};
int main(a) {
union Data data;
printf("Data length =%lu\n".sizeof(data));
data.a = 1;
data.c = 10.00;
strcpy(data.b, "Test data");
printf("Data % d \ n",data.a);
printf("Data \ n % f",data.c);
printf("% s \ n data",data.b);
return 0;
}
Copy the code
Data length =100data- 393497114.data5278115000342806695772160.000000Data Test dataCopy the code
We see that the values of data A and C members are corrupted because of the memory space occupied by the last variable assigned, which is also the reason for the correct output of the b variable
We can only use one variable at a time
#include <stdio.h>
#include <string.h>
union Data {
int a;
char b[100];
float c;
};
int main(a) {
union Data data;
printf("Data length =%lu\n".sizeof(data));
data.a = 1;
printf("Data % d \ n",data.a);
data.c = 10.00;
printf("Data \ n % f",data.c);
strcpy(data.b, "Test data");
printf("% s \ n data",data.b);
return 0;
}
Copy the code
Data length =100data1data10.000000Data Test dataCopy the code
Here all members are printed correctly because only one variable is used at a time
18 typedef
C provides the typedef keyword, which you can use to give a type a new name
#include <stdio.h>
typedef unsigned int TEXT;
int main(a){
TEXT a = 11;
printf("Parameter =%d\n",a);
return 0;
}
Copy the code
Parameters for =11
Copy the code
You can also give user-defined data types new names, such as structs
#include <stdio.h>
#include <string.h>
typedef unsigned int TEXT;
typedef struct BOOKS {
char a[50];
char b[50];
} Book;
int main(a) {
TEXT a = 11;
printf("Parameter =%d\n", a);
Book book;
strcpy(book.a, 1 "test");
strcpy(book.b, "The test 2");
printf("a=%s\n", book.a);
printf("b=%s\n", book.b);
return 0;
}
Copy the code
Parameters for =11A = test1B = test2
Copy the code
The difference between typedef and #define
#define is a C instruction used to define aliases for various data types. It is similar to a typedef, but with the following differences
typede
F is limited to defining symbolic names for types,#define
You can define aliases for values as well as for typestypedef
To interpret execution for the compiler,#define
Processing for the precompiler
#define TRUE 0
#define FALSE 1
int main(a) {
printf("Value =%d\n", TRUE);
printf("Value =%d\n", FALSE);
return 0;
}
Copy the code
Values for =0Values for =1
Copy the code
19 Input and output
Getchar () & putchar() functions
The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only one character at a time. You can use this method within a loop to read multiple characters from the screen.
The int putchar(int c) function prints the character to the screen and returns the same character. This function outputs only one character at a time. You can use this method within a loop to output multiple characters on the screen.
#include <stdio.h>
int main(a){
printf("Please enter a character \n");
int a = getchar();
printf("Your input is \n");
putchar(a);
printf("\n");
}
Copy the code
Please enter a character text and your input is tCopy the code
The gets() & puts() functions
The char *gets(char *s) function reads a line from stdin to the cache pointed to by S until a terminator or an EOF int puts(const char *s) function writes a string S and a trailing newline to stdout
#include <stdio.h>
int main(a){
char a[100];
printf("Enter your character \n");
gets(a);
printf("You typed the character \n");
puts(a);
return 0;
}
Copy the code
So you type your character text and you type your character textCopy the code
Scanf () and printf() functions
int scanf(const char *format, …) The function reads input from the standard input stream stdin and browses the input according to the format provided.
int printf(const char *format, …) The stdout function writes output to the standard output stream and produces output in the format provided.
Format is a simple constant string, but you can define %s,%d,%c,%f to read strings, numbers, characters, floating point numbers
#include <stdio.h>
int main(a) {
char a[100];
int b;
printf("Enter text \n");
scanf("%s%d", a, &b);
printf("Your input text =%s,%d\n",a,b);
return 0;
}
Copy the code
Input text123The text that you type =text,123
Copy the code
20 File Reading and Writing
#include <stdio.h>
int main(a) {
FILE *file;
// Open the file to allow reading and writing, or create the file if it does not exist
file = fopen("/Users/renxiaohui/Desktop/test.txt"."w+");
// Write a line
fprintf(file, "this is a text\n");
// Write one more line
fputs("this is a text aaaa\n", file);
fclose(file);
}
Copy the code
Create file test.txt and write two lines of text
#include <stdio.h>
int main(a) {
FILE *file1;
char a[255];
// Open a file, read only
file1 = fopen("/Users/renxiaohui/Desktop/test.txt"."r");
// Reads the file and stops reading when it encounters the first space or newline character
fscanf(file1, "%s", a);
printf("1= %s\n", a);
// Reads the string into the buffer and encounters a newline or EOF return at the end of the file
fgets(a, 255, file1);
printf("2= %s\n", a);
fgets(a, 255, file1);
printf("3= %s\n", a);
// Close the file
fclose(file1);
}
Copy the code
Read the file you just created
1= this
2= is a text
3= this is a text aaaa
Copy the code
21 Preprocessor
C preprocessors are not part of the compiler, they are a separate step in the compilation process, and they do the required preprocessing before the compiler actually compiles
All preprocessors begin with (#), which must be the first non-null character. For readability, preprocessors should start with the first column. The most important preprocessors are listed below
instruction | describe |
---|---|
#define | Define the macro |
#undef | Undefine macros |
#include | Contains a source file code |
#ifdef | Returns true if the macro is already defined |
#ifndef | Returns true if the macro is not defined |
#if | Compile the code if the given condition is true |
#else | # Alternative to if |
#elseif | If the previous #if given condition is not true and the current condition is true, compile the following code |
#endif | End with a #if. # the else statement |
#error | When standard error is encountered, an error message is output |
#pragma | Use standardized methods to issue special instructions to the compiler |
Precompiler instance
#define MAX 20
Copy the code
This directive says that defining all MAX values as 20 and using #define to define constants increases readability
#include <stdio.h>
#include "myheader.h"
Copy the code
The first represents getting the stdio.h library from the system library and adding it to the source file, and the second represents getting myheader.h from the local directory and adding it to the source file
#undef FILE
#define FILE 99
Copy the code
Undefine FILE and redefine it to 99
#ifdef MESSAGE
#define MESSAGE "you wish"
#endif
Copy the code
This means that MESSAGE is defined as you wish only if MESSAGE is undefined
Predefined macro
Macros are predefined in ANSI C and can be used programmatically, but their values cannot be changed
The macro | describe |
---|---|
1__DATE__ | The current date, a character constant in the format “MMM DD YYYY”. |
1__TIME__ | The current time, a character constant in “HH:MM:SS” format. |
1__FILE__ | This will contain the current filename, a string constant. |
1__LINE__ | This will contain the current line number, a decimal constant. |
1__STDC__ | Is defined as 1 when the compiler compiles to ANSI standards. |
Look at the use of
#include <stdio.h>
int main(a) {
printf("data=%s\n",__DATE__);
printf("file=%s\n",__FILE__);
printf("time=%s\n",__TIME__);
printf("line=%d\n",__LINE__);
printf("stdic=%d\n",__STDC__);
return 0;
}
Copy the code
data=Mar 31 2020
file=text27.c
time=15:31:49
line=19
stdic=1
Copy the code
The parameterized macro
Parameterized macros can simulate functions, for example, here is a way to square a number
int square(int x) {
return x * x;
}
Copy the code
Can be represented by parameterized macros
#define square(x) ((x)*(x))
Copy the code
Parameterized macros must be defined with #define before they are used. The parameter list must be enclosed within parentheses and must immediately follow the macro name without Spaces
#define square(x) ((x)*(x))
int main(a) {
printf("Squared =%d\n",square(5));
return 0;
}
Copy the code
Square for =25
Copy the code
Preprocessing operator
Macro continuation operator (\)
A macro is usually written on a single line, but if the macro is too long to fit on a single line, the macro continuation operator (\) is used for example
#define message_for(a,b) \
printf(#a"and "#b"we are friend\n")
Copy the code
String constant quantization operator (#)
In macro definitions, we use the string constant quantization operator (#) when we need to convert a macro parameter to a string constant. For example:
#define message_for(a,b) \
printf(#a"and "#b"we are friend\n")
int main(a) {
message_for("xiaoming"."xiaohong");
return 0;
}
Copy the code
"xiaoming"and "xiaohong"we are friend
Copy the code
The ** tag paste operator (##) **
Look directly at code comparisons
#define add(n) printf("token" #n " = %d\n",token##n)
int main(a) {
int token34 =40;
add(34);
return 0;
}
Copy the code
token34 = 40
Copy the code
How does this happen, because this actually produces the following actual output from the compiler
printf ("token34 = %d", token34);
Copy the code
The defined () operator
The preprocessor defined operator is used in constant expressions to determine whether an identifier has been #define, true if it has been defined, and false if it has not
#if! defined(TEXT)
#define TEXT "text\n"
#endif
int main(a) {
printf(TEXT);
return 0;
}
Copy the code
text
Copy the code
22 the header file
Header files are.h files that contain function declarations and macro definitions. There are two types of header file system header files and c programmers write their own header files
It is recommended in C programs to write all constants, macros, system global variables, and function prototypes into header files
Importing header files
Use the preprocessing command #include to introduce header files of two types
#include <file>
Copy the code
This form is used to refer to system headers, which are searched in the system directory
#include "file"
Copy the code
This form is used to refer to the user header file, which he searches in the current file directory
Reference the header file only once
If a header reference is referenced twice, the compiler will process the contents of both headers, which will generate an error. To prevent this, it is standard practice
#ifndef HEADER_FILE
#define HEADER_FILE
the entire header file file
#endif
Copy the code
If HEADER_FILE is not defined, the import header file is defined, and if the next reference is made because HEADER_FILE has already been defined, it will not be introduced again
Look at this article for the difference between dot h and dot c
www.cnblogs.com/laojie4321/…
23 Error Handling
When an error occurs in C, most C’s return 1 or NULL and set an error code errno. The error code is a global variable that indicates that an error occurred during the execution of the function. You can find various error codes in the errno
Therefore, the programmer can use the return value to determine whether there is an error. It is a good programming habit for the developer to initialize errno to 0 during initialization. 0 means there is no error
Errno, perror(), and strerror()
The C language provides perror() and strError () to display errno-related text information
perror()
Function: it will display the text you pass in followed by a colon anderrno
Relevant text informationstrerror()
Function: Returns a pointer to the text representation of the current errno value.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(a) {
FILE *pf;
int errnum;
pf = fopen("aaa.txt"."rb");
if (pf==NULL) {//stderr, output to screen
printf("Error number %d\n",errno);
fprintf(stderr."Error %s\n",strerror(errno));
perror("Perror display error");
}
return 0;
}
Copy the code
Error number for2Error No such fileorDirectory perror Displays an error: No such fileor directory
Copy the code
24 Memory Management
C provides several functions for memory allocation, which can be found in the <stdlib.h> file header
function | describe |
---|---|
void *calloc(int num, int size); | Dynamically allocate num contiguous space of size and initialize each byte to 0 |
void free(void *address); | This function frees the memory block pointed to by address, freeing dynamically allocated memory |
void *malloc(int num); | Allocate a specified amount of memory in the heap to store data. This amount of memory is not initialized after the function is executed. Their values are positional |
void *realloc(void *address, int newsize); | This function reallocates memory, and the new memory is allocated to the newsize size |
Note: void* represents a pointer of undefined type. A void* pointer can be cast to a pointer of any other type
Dynamically allocated memory
If you know the size of an array in advance, it will be easier to define an array, such as one that can hold 100 characters
char name[100];
Copy the code
But if you don’t know how much text you need to store, you need to allocate memory dynamically
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(a) {
char a[100];
char *b;
strcpy(a, "Fixed array 100");
// Dynamically allocate memory
b = (char *) malloc(200 * sizeof(char));
// b= calloc(200, sizeof(char));
if (b == NULL) {
printf("Memory allocation failed");
} else {
strcpy(b, "Dynamic memory allocation succeeded");
}
printf("Value = % s \ n",b);
// Reallocate memory
b = realloc(b, 500 * sizeof(char));
if (b == NULL) {
printf("Memory allocation failed");
} else {
strcpy(b, "Memory reallocation succeeded");
}
printf("Value = % s \ n",b);
// Free memory
free(b);
return 0;
}
Copy the code
The value is = Succeeded in dynamically allocating memory. The value is = Succeeded in reallocating memoryCopy the code
The code above for allocating memory can also be replaced by
b= calloc(200.sizeof(char));
Copy the code
25 Command line parameters
Arguments can be passed from the command line to the program when it executes. These values are command-line arguments. Command-line arguments are handled by the main function arguments, where argc is the number of arguments passed and argv[] is an array of Pointers to each argument passed to the program
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc == 2) {
printf("Parameter %s\n", argv[1]);
} else if (argc > 2) {
printf("More than two parameters \n");
} else {
printf("Only one argument \n");
}
return 0;
}
Copy the code
L-96FCG8WP- 1504.:untitled renxiaohui$ gcc text30.c
L-96FCG8WP- 1504.: Untitled renxiaohui$a.out text The value is textCopy the code
reference
www.runoob.com/cprogrammin…