C language learning notes


Using Xcode to initialize a C language project

  1. Open Xcode and select “create a new Xcode project”
  2. Select MacOS / command line tool and click next
  3. Fill in product name (HelloWorld) and organization identifier (organization authentication) cn.hifelix.ios ), select language as “C”
  4. Write in main. C
#include <stdio.h>
int main () {
  printf("This is my first Xcode C project! \n");
  return 0;

Xcode two commonly used shortcut keys

  1. Command + R compiles and executes automatically
  2. Conmand + B auto compile (check for errors)

Add multiple targets for project

Common data types

int float double char
Int (integer) – 2147483648 ~ + 2147483647
Float (single precision floating point type) a decimal whose significant digits are not more than 7 digits (more than 7 digits cannot be saved accurately, and the first 7 digits can be saved accurately)
Double (double precision floating-point type) a decimal whose significant digits are not more than 16 digits (more than 16 digits cannot be saved accurately, and the first 7 digits can be saved accurately)
Char character type

Declaration of variable

int a;

Assignment of variables

Int type
int num;
num = 100;

Float type
Assign a value to a variable of type float
·In C language, if you write a decimal directly, the data type of the decimal is double
·Float can only save the decimal with the significant digits less than 7, and the part beyond it will not be saved accurately
float f1;
F1 = 12.12f (double if 12.12 is written)

Double type
double a;
a = 12.12

Char type
·Char variable can only store a single character, and a single character should be enclosed with a single quotation mark
·If too many characters are given, save the last one
·Space is also a character, so you can save a space
·Char variable cannot store Chinese (3 bytes for one Chinese, 1 byte for one char variable)
char ch;
ch = ‘a’;

The value of the output variable

·Printf (“output information”);
The content in double quotation marks is output as is
·Printf (“format control string”, variable list)
The output variable type is different, and the space occupying symbol is different
int a;
a = 18;
Print (“the value of variable a is% d”, a));
%F — float type placeholder (default output 6 digits after decimal point)
%D — int type placeholder (default output 6 digits after decimal point)
%LF — double type placeholder
%C — char type placeholder
Output the values of multiple variables at a time
int a = 10;
float b = 10.12f;
Printf (“int a’s value is% D, float B’s value is% F”, a, b));

Declare multiple variables

int a, b, c, d;
int a = 1, b = 2, c = 3, d = 4;

Naming rules of variables

·Variable name can only start with any letter, underline and $, not with a number
·It can be followed by letters, numbers, underscores and $
·Cannot use C language keywords
·C language is strictly case sensitive

The use of scanf function

Syntax format:
Scanf (format controller), variable address list;

Use scanf function to receive input data of other types
What type of data you want the user to input is determined by the placeholder in the format controller

%D the user enters data of type int
%F user enters data of type float
%LF user enters data of double type
%C user input char type data

  1. First declare a variable, and the type of the variable should be consistent with the type of the data entered by the user
  2. Using scanf function to let users input data
    a. In the format controller, the corresponding placeholder must be negotiated
    b. To store the user input data in which variable, write the address of the variable at the end, and then you can get the address of the variable
int main () {
float f1 = 0.01f;
scanf("%f", f1);
  1. Using scanf function to receive multiple data input by users
    a. You can write multiple placeholders in the format controller. The number of placeholders represents the number of data to be entered by the user, and the type of placeholders represents the type of data entered by the user
    b. Write the address of the variable that stores the data entered by the user later
    c. Users can use spaces or carriage returns to split multiple data when they input numbers

Clear the data in the buffer


Arithmetic operator

The type of the result of an arithmetic expression
a. Two operands of the same type, the type of the result after operation is the type of the two operands;
b. If the types of two different types of operands are inconsistent, the result is the type int < float < double with higher precision

Self increasing / self decreasing expression

The result of the former auto increase / Auto decrease expression is the result after auto increase / Auto decrease, and the result of the latter auto increase / Auto decrease expression is the variable itself, and then the auto increase / Auto decrease operation is performed

Boolean value

In C language, int is used to represent Boolean value, 0 represents true, and non-0 (1) represents false

Logical expression

! wrong

Format code shortcut (Ctrl + I)

Scope of variable

Variables in braces are recycled after the code in braces completes itself

The method of generating random number by C language

  1. First introduce a system header file

    inclde <stdlib.h>

  2. Call the arc4random function
    Passing in an integer n will return a random number of 0 ~ (n – 1)
    int num = arc4random(10);
    A random number of 0-9 will be generated and assigned to num

Notes on switch case syntax

Switch (expression)
    case: 1:
    Printf ("this is case1");
    case: 2:
      int a = 1;
      Printf ("the value of int a is% d", a)

Goto statement (loop can be implemented)

Syntax: the loop is an identifier and can be named by itself

Note: the code under identifier cannot declare variable (in C language, variable cannot be declared after identifier);

int main () {
    print("Mr Chan");
  print("Mr Feng");
  goto loog;

Use of function

Note: the function needs to be defined outside the main method, otherwise an error will be reported!

Declaration of function

void test();                                             #  Function declaration (equivalent to variable promotion)
int main () {
The definition of void test () {# function
  Printf ("here is the definition of the function");

preprocessor directives

The code of C language is mainly divided into two types

1) C code

2) preprocessing code

For example, include < stdio. H >

Classification of preprocessing instructions

The file contains the instruction “include”

Macro definition

Conditional compilation instruction # if

The file contains instructions

Function: can copy the specified file content to the specified place


Include “file path”

Include < file path >

The differences between the two grammars are as follows

Use “” to find this file in the directory where the current source file is located. If there is one, it will be included directly. If there is no one, it will be found in the compiler directory of the system. If there is one, it will be included. If there is no one, it will report an error

Use < > include to directly search the compiler directory of the system. If there is, include it. If there is no, report an error

Use: # include “/ user / hifelix / desktop / 1. TXT”

Four bases in C language


Write (add 0b before the number), for example: int num = 0b10001010101010;

octal number system

Writing method (add 0 to the front of the number): for example: int num = 0133;

decimal system


Write it in the following way: int num = 0x167acde;


%D output the data in integer variable in decimal system;

%O output the data in integer variable in octal;

%X outputs the data in the integer variable in octal;

Variable memory size

Int 4 bytes

Double 8 bytes

Float 4 bytes

Char 1 byte

Bit operation

1. Bitwise and operation&

2. Bitwise OR operation|

3. Reverse by position ~ 3

4. Bitwise XOR 3 ^ 2 (same 0, different 1)

5. Press bit to move left or right < > >

Int type modifier

Short modifier

Short int num = 10, let int only occupy two bytes, and the maximum number can be expressed to the 15th power of 2

Short int variable output placeholder% HD

The declaration of short int variable can omit int, for example: short num = 10;

Long modifier

In a 32-bit operating system, the long modifier takes up four bytes

In a 64 bit operating system, the long modifier takes up 8 bytes

Long int variable output placeholder% LD

Long long modifier

Long long int variable output placeholder% LLD

In both 32-bit and 64 bit operating systems, the long long modifier takes up 8 bytes

Unsigned modifier

The highest bit of the number is not used to denote the sign unsigned int num = num

Unsigned int variable output placeholder% U

Unsigned short variable output placeholder% Hu

Unsigned long variable output placeholder% Lu

Unsigned long long variable output placeholder% LLU


a. In an array, multiple data of the same storage type are specified when we create them
b. The number of data that can be stored in an array is fixed, which is specified when we create it

Declaration of array

Int arr [4] >

Storing data in an array

arr[1] = 100

Initialization of array (if only one value is initialized, other values will be initialized to 0)

int arr[3] = { 10, 20, 30 }

int arr[] = { 10, 20, 30, 40, 50}

int arr[3] = { [1] = 10, [2] = 20 }

Calculates the length of the array

int lenth = sizeof(arr) / sizeof(int);

Two dimensional array

Declaration of two dimensional array

Int arr3 (declare an array of 3 rows and 4 columns);

Assignment of two dimensional array

arr1 = 100;

Initialization of two dimensional array

  1. int arr3 = {
    {1, 23, 44},
    {2, 22, 11},
    {12. 45, 75},
    {223. 99, 64},
  2. The number of rows can be omitted, for example
    int arr[][4] = {
    {1, 23, 44},
    {2, 22, 11},
    {12. 45, 75},
    {223. 99, 64},
  3. Omit the braces inside
    int arr3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
  4. Partial initialization (the first element of the first one-dimensional array is initialized to 10, the first element of the second one-dimensional array is initialized to 10, the first element of the third one-dimensional array is initialized to 10, and all others are initialized to 0)
    int arr3 = {{10}, {20}, {30}}
  5. Partial initialization (in order, the rest will be initialized to 0)
    int arr3 = {1, 2, 3, 4}
  6. Initialization of character array (if only some elements are initialized, other characters will be initialized as an invisible element, and nothing will be printed out. The ASCII code of this character is 0)
    chat chr[4] = { ‘a’ };

String data (in C language, string array must be enclosed with double quotation marks)

Declaration of string array

  1. char name[] = { ‘j’, ‘a’, ‘c’, ‘k’, ‘\0’ }
  2. Char name [] = {“Jack”} # will be automatically added after
  3. The most commonly used way is char name [] Jack;
  4. char name[10] = “jack”; There will be 5 after that
  5. One Chinese takes three bytes

Output of string array

Format controller% s
Principle: start from the specified string array address, and output from low byte to high byte by byte until the end of the encountered 0

The length of the string array

You need to use the while loop
int len = 0;
while (name[len] != ‘\0’) { len++ };
At the end of the loop, you can get the length of the string

String common functions

———————–These two functions are in stdio. H file and can be used directly—————————-

  1. Puts() function
    Function: used to output string
    Syntax format: puts (string array name)
    Advantages: after output, automatically wrap
    Disadvantage: you can only output strings, and you cannot use placeholders
  2. Get() function
    Function: receive 1 string data from the console
    Syntax format: gets (string array name)
    Advantage: when the data entered by the user contains spaces, it will receive them together with spaces
    Disadvantages: like scanf function, it is not safe (when the string array used to store string data is not long enough, the program will crash)

———————–The following four functions are declared in the string. H header file—————————-

  1. Strlen() function (return value type is unsigned long)
    Function: get the length of string data stored in character array
  2. Strcmp() function
    char name1[] = “jack”;
    char name2[] = “rose”;
    strcmp(name1, name2);
    Compare the size of two strings (compare the size of the first character, if the first character is the same, compare later)
    The return value is int type, greater than 0, name1 large, equal to 0, the same large, less than 0, Name2 large
  3. strcpy
    char name1[] = “jack”;
    char name2[] = “rose”;
    strcpy(name1, name2);
    Copy the value of Name2 to name1

6. Strcat() string data splicing

Clear print information — > system (“clear”);

Pointer (the pointer is the address of the variable)

Pointer variable

Declaration of pointer variable

intp1;( Declared an object of type int/Int pointer type variable named P1 pointer variable)

It can also be written as: intp1; int p1;

Batch declaration: int p1, p2, *p3;

Initialization of pointer variable

int num = 100;

int* p1 = &num;

If you do not initialize an address for the pointer variable, at least initialize a null or 0 value for the pointer variable, so as not to cause the wild pointer pointing to be unknown and lead to the program bug
int p1 = null; int p1 = 0;

The use of pointer variable

p1 = 100; (P1) points to num;

Five areas in memory (no matter which area is used to store data)

Stack area, heap area, BSS segment, data segment / constant area, code segment

Stack area

Used to store local variables

Heap area

Allows programmers to manually request space from the heap to use

BSS section

Used to store uninitialized global variables and static variables

Data segment

Used to store initialized global variables, static variables and constant data

Code snippet

Code / instruction used to store programs

Use fputs to output string data to the specified stream

Stream: standard output stream — > console

Char * name = Chen Feng;
     fputs(name, stdout);
   File stream > files on disk
     1) Declare a pointer to a file on disk
        The fopen function creates a pointer to a file
        Two parameters of fopen function
           The first parameter: the path of the file, which means that the created pointer points to the file
           Second parameter: operation mode of this file (W: write, R: read, a: append)
     2) Use fputs to write the string to the specified file
        Fputs (string, file pointer);
     3) After writing, be sure to use fclose() to close the file

Use fgets to get the content from the specified stream

fgets(name, 10, stdin);

Malloc function / calloc function / realloc function

All three functions are declared in the system header file of stdlib. H

Malloc function

int *p1 = malloc(4);
Function: to apply for the space of specified bytes to use
Parameter: size_ t(unsigned long)
Return value: void *, representing pointer without type

Free space (pointer);

Calloc function

Advantages over malloc
1) You can pass in sizeof (int) to specify the size of the space
2) The garbage value of the space is initialized
int *p1 = calloc(4, sizeof(int));

Relloc function (expansion)

Pointer to function

1) A pointer to a function can not be pointed to by any function

2) Grammar
Return value type (* pointer name) ([parameter list])
void (*pFuction)();
Represents the declaration of a pointer to a function called pfunction
This pointer can only point to functions that have no return value and no arguments
int (*pFun)(int num1, int num2);

3) Initialization
void test () {}
void (*pFunc)() = test;

4) Call
Or (* pfunc) ();

structural morphology

Syntax format:

New type name of struct
     //Write here that the new type you created is a combination of those variables
     Data type 1 small variable name 1
     Data type 2 small variable name 2
     Data type 3 small variable name 3


  struct Student
     char *name
     int age
     int score
     float height

Declare variables of structure type

Grammatical format
     Struct new type name variable name;
     struct Student stu;

Initialization of structure variables

The first initialization method:
     stu.name = "felix";
     stu.age = 18;
     stu.score = 95;
     stu.height = 180;
  The second initialization method is as follows:
     struct Student stu = { "felix", 18, 95, 180 };
  The third initialization method (initialization of specified members)
     struct Student stu = { .name = "felix", .age = 18, .score = 95, .height = 180 };

Macro definition


#Define macro name, macro value 
  #define N 10;


  int a = N + 1;

Conditional compilation instruction


if N > 0

Printf (“hehe”)

elif N > 0

Printf (“hehe”)

else N > 0

Printf (“hehe”)


Ifdef n (if n macro is defined)

Ifndef n (if n macro is not defined)

Static and external

Static modify local variables: variables are saved in constant area (static variables), and static int num = 123 is called for the second time; It will not be declared again, but used directly
Static global variables cannot be accessed across modules, and extern global variables can be accessed across modules

Recommended Today

Using IOS airprint to realize printing function

content 1. What is airprint In fact, it is to print the content on IOS (iPhone, iPad) with a printer that supports airprint. Wireless control of printing process, very convenient. 2. First hand information Learning IOS, the first-hand information must be Apple’s official documentshere。 ( What I’m going to describe below is basically a summary […]