The first part object-c fundamental

Source: Internet
Author: User
Tags variable scope

Day02 Basic Knowledge

One, variable

1. Type char, integer int, floating-point type float/double, pointer, structure, UNION, etc.

2. Declare the type and declare it only once before each use

int number1;//declares the variable number1 and opens up (int type) memory space.

3. Declare a variable before it is used, it is possible to have a value, but it is better to give it an initial values.

int number3=0;

4. Value of the output variable

%d int

%f float

%LF Double

%c Char

printf ("%d", Number3);

Day03 Data Type

First, the data type

1. Data type classification

A. Basic data types

B. Reference data types (follow-up)

2. Basic data types

In the C language, there are four basic data types: char, int, float, double

Second, character Char

Common characters:

' A ' = 65, ' A ' = 97, ' 0 ' = 48

1.char represents a character, enclosed in "8-bit (8bit) memory.

2. Input function

scanf ("%c", &ch);

Transmits data to the program through the keyboard, waiting for (blocking) user input. Until the user has entered, the default is to enter the end of user input, CONTROL+C forces the program to stop running.

3. Escape character \

Common escape character handling:

\ nthe newline character (the line at the beginning of the next line)

\ r Carriage return character (beginning of bank)

\ t tab (equivalent to press TAB)

integer int

1.short (int) 16-bit, long (int) 32-bit, long long int represents a 64-bit integer. The recommended int type describes integers.

2. Binary conversion Automatic

1). Assigning values

int i = 11;//default decimal

int i2 = 011;//octal

int i3 = 0x11;//hex

2). Output

printf ("i:%d i:%o i:%x\n", i,i,i);

Four, floating-point type float/double

In the 1.C language, floating-point types include float, double, long double.

Float 32-bit 4-byte 2^32

Double 64-bit 8-byte 2^64

Long double 96-bit 12-byte 2^96

2. When outputting results, use placeholders

%f->float

%lf->double

%g

The result of%.2f output retains two decimal places

Day04 operator

One, constant

1.

3-int

3l-long int

3ll-long Long int

3u-unsigned int

3ul-unsigned Long

2.

3.5-double

3.5f-float

3.5l-long Double

Ii. sizeof (parameter)

1. Calculate the amount of memory space that the data occupies, in units of bytes.

2. A parameter can be a type, a variable, or an expression, but sizeof () is not responsible for evaluating the value of an expression, but only about the type.

3.sizeof (parameter) the corresponding data type is long unsigned int->%ld

Third, operator

1. Arithmetic operators

a.+ 、-、 *

B./(seeking quotient) and% (for redundancy, modulo)

2. Assignment operator =

A. Assignment from right to left

int i = 10; int j=20,k=30;

i=j=k=6; Note: not recommended

B. Assignment can be used in conjunction with other operators, called compound assignment

I+=3 i = i + 3

Advantage: + = (one operand) more efficient than = + (two operands)

3. Self-increment, decrement operator (+ + or--)

B. Can be used for integer variables Int/short/long, floating-point float/double, and character char variables.

4. Relational operators

A. In C, the relational operator corresponds to the mathematical >, <, >=, <=, = = equals,! = does not equal, the expression produces the result, 1 (established) or 0 (not established)

B. Relational operators can also be used to compare integers and floating-point numbers, as well as to allow mixed-type operands.

5. Logical operators && and, | | OR,! Non-

A. When the operand processing result is not 1 or 0 o'clock, the logical operator takes a non-0 operand as the truth value.

B. Short-circuit operation

6. Take address & and addressing operators *

A. Add & to the variable before it, and get the address of the variable in memory

B. Use the * addressing symbol in front of the address to get the data and value saved by the address.

int i=20;

printf ("%p\n", &i);

printf ("%d", *&i);

7. Type Conversion

A. Type upgrade

Floating point is higher than integer, long integer is higher than short integer, signed and unsigned, and in C language, type conversion is not prompt.

High long double

Double

Float

Long Long

Long

Low int

B. Other conversions

1) floating-point and integer operations, converting floating-point (double) operations

2) The operation of Short/char is converted into int

C. Coercion type conversions can be used

Target type variable = (target type) source type variable;

Note: When a type is converted, it actually creates a new variable (opens up a new memory space), and the original variable remains unchanged.

8. Conditional operator Multi-mesh operator trinocular operator

1). Syntax format: conditional expression-expression 1: expression 2;

2). When expression 1 and expression 2 are different base types, the higher-precision types are automatically converted.

9. Comma operator

Expression 1, expression 2, expression N;

1). Computes the value of each expression in turn, using the value of the expression n as the result of the entire expression

int result= (i=10,j=20,k=30);//30

2). Not all occurrences of commas appear in the comma expression: int i,j,k;

10. Precedence of Operators

Muzzle operators: (), [],.

| Monocular operators:!, + + 、--、 type conversion, &, *, sizeof ()

| Arithmetic operators: First *,/,%, after plus, minus

| Relational operators:>, >=, <, <= higher than! =, = =

| Logical operator:! above && above | |

| Conditional operator:?:

| Assignment operators: =, + = ... Compound assignment

Low comma operator:,

Day05 Process Control

One, Switch branch (select branch)

Switch (control expression) {

case constant expression 1: statement;

Case constant Expression 2: statement;

case constant expression N: statement;

Default: statement;

}

Control expressions are treated as Integer data, or character data processing, but not floating-point numbers and strings. Constant expressions must be constants (integers and characters), and duplicates are not allowed.

Day06 Loops

One, for loop

A.for (;;) compile will not error, the number of cycles is indeterminate, the cycle of death. CTRL + C forces the loop to terminate.

Day07 Array

One, array

1. Disclaimer

int array[3];

2. Initialization

A. Value assigned to use

int array2[3]={3,4,5};//assigns values to array elements in turn

int array4[3]={1,2};//automatically fills the following values with zeros

B. Assign 0 value

int array[3];//is not initialized when there may be garbage

Each element in an int array3[3]={0};//array is 0

3. Remove the value of the array element

printf ("array4[2]:%d\n", array4[2]);

4. Length of the array

Long size = sizeof (array)/sizeof (array[0]);

Two, multidimensional arrays

2. Declaring a two-dimensional array

int array2[3][2];

3. Initialization

int array2[3][2]={{1,2},{3,4},{5,6}}; Assign values in turn

int array2[3][2]={1,2,3,4,5,6};

int array2[3][2]={1,2,3,4};//Auto Complement 0

Day08 function

First, the function

1. Function declaration

A. Return value type function name (parameter);

B. A function declaration can omit a parameter, and an omitted parameter represents an arbitrary argument that can be accepted if no arguments are required, using the Void keyword. void f (void);

C. When the parameter is an array, takes two parameters, the first parameter is the length of the array, the second parameter is an array (array name) that does not specify the length of the array

void getsum (int length,int arr[]) {}

int main ()

{

int arr[]={1,2,3,4};

Getsum (4,arr);

return 0;

}

E.exit (0) Two keywords

Exit (0) is a function that exits the entire program needs to contain a stdlib.h

Day09 Scope and life cycle of function variables

One, variable scope

A. Local variables: variables defined in a function are called local variables

B. Global variables: variables defined outside the function are called global variables

C. Global variables can be used by multiple functions, while local variables can only be used by the current function.

D. When the global variable and local variable name, still adhere to the nearest principle.

E. Parameters also have scopes, which are internal to the function.

Second, the variable life cycle

A. When modifying a local variable with auto (default), when declaring a variable, the memory space is created, and when the variable goes out of scope, the corresponding memory space is eliminated.

B. When modifying a local variable with static local variable, the lifetime of the variable will be longer and long until the end of the program, although the lifetime of the static variable is longer, but the scope is still inside the function.

C.auto can not modify global variables

D.static can modify global variables

Third, the pointer

1. The pointer refers to the memory address.

2. The variable that holds the pointer is called the pointer variable.

3. Declaring a pointer variable

int i=3;

int *p=&i;

printf ("%p\n", &i);

printf ("%p\n", p);//The value of the pointer

printf ("%d\n", *p);//The value that the pointer points to

4. Use of pointers:

A. Pointers can be used for parameters, passing the address of a variable, which is equivalent to multiple functions sharing memory address (memory space).

void Change (int* p1,int* p2) {

int temp=*p1;

*P1=*P2;

*p2=temp;

}

int main ()

{

int i=3,j=4;

Change (&I,&J);

printf ("%d%d\n", i,j);

}

B. Pointers can also be used as return values, but do not return automatic variables, because when a function ends a local variable is automatically cleared (freed). Solution: Extend the life cycle.

C. pointers support adding integers, subtracting integers, comparing and subtracting pointer values, but the units of the operation are determined by the type of the pointer.

int type pointer +1 = Address +4

Char type pointer +1 = Address +1

D. Pointers and arrays

int array[3]={10,20,30};

int* P=array;

printf ("%p\n", p);//The value of the pointer

printf ("%p\n", p+1);

printf ("%d\n", * (p+1));//20

Day10 string

One, the string

1. Concept: A set of character arrays, starting with the first address of the array, with ASC's ' \ S ' as The Terminator.

2. The difference between a string and an ordinary array: The normal array does not have an end identifier, and the string is there.

3. How strings are defined:

A. Literal "Hello"

B. Using a character array to define a string

Char str[10]={' H ', ' e ', ' l ', ' l ', ' o ', ' n '};

C. Using the character pointer char* p1 = str;

printf (p1);

printf ("%s", p1);

4. Differences in how strings are created

A. Declared variable, placed in the memory of the stack area.

B. Literals create a string that is placed in the in-memory code area If you create a string and the value is the same, only one memory area is created, the value is read-only, and the value cannot be changed.

C. A string created using an array method, placed in an in-memory stack, can create multiple identical strings whose values can be changed.

D. A character pointer, which simply points to an area of memory.

5. Enter

A.SCANF () There is a buffer problem when entering characters

Pass scanf ("%*c"); Clear buffer

Char name[10];

scanf ("%s", name);//Auto-add

B.SCANF () does not have a buffer problem when entering a string, but there is a security issue (memory overflow).

C.fgets () function to resolve security issues

Syntax format: fgets (parameter 1, parameter 2, parameter 3);

Parameter 1: Save the first position of the data, parameter 2: The length of the save (including The Terminator); parameter 3: How to get the data

Note: When inputting data using the Fgets method, it will automatically add ' \ n ' after the data

6. Output

printf () differs from puts.

printf () requires manual line wrapping and can output strings multiple times

Puts () wrap, output string content only once

Char str[10];

Fgets (Str,5,stdin);

printf ("%s\n", str);

Puts (str);

const keyword

The variable can be read-only, and the value of the variable can be changed only at initialization time, and this variable is constant.

Const int* p = &i; The value pointed to by the pointer becomes read-only

int* Const P = &i; The value of the pointer becomes read-only

7. Array of pointers (array of strings)

The elements in the array are pointers, pointers, and string arrays

1) Save multiple string header addresses

2) define pointer array

char* array[3]={"Guanyu", "Zhangfei", "Liubei"};

3) Traversal

for (int i = 0; i<3;i++) {

printf ("array[%d]:%s\n", I,array[i]);

}

8.C Language String Function library

A. #include <string.h>

B. Copy of String strcpy (STR2,STR)

C. Concatenation of Strings strcat (STR3,STR)

D. Length of string strlen (str), length of string, not including Terminator

Char str[10];

char* p1= "Hello";

char* p2= "You";

strcpy (STR,P1);

strcat (STR,P2);

unsigned long len=strlen (str);

printf ("%lu\n", Len);//8

E. Two string comparison strcmp (STR,STR1), with a result of 0 o'clock, two strings equal.

Char str1[10]={' A ', ' B ', ' C ', ' n '};

char* str2= "ABC";

int result=strcmp (STR1,STR2);

printf ("%d", result);

Two, macro

Macro equivalent to text substitution operation

1. Macro definition

A. Defining the outside of the function

B. Format: #define PI 3.14//replace pi content to 3.14 before compiling

C. Differences between macros and global variables

1) macros are equivalent to text substitution operations, which do not exist in memory

2) Global variables exist in memory

2. Macro function: #define Mianji (R) pi*r*r//Note parameter is no data type

Day11 large programs and composite types

A, macro

1. #x delegate to convert the X content to a string

#define STR (x) #x

2.# #x represents a new identity by stitching the contents of the logo with other content

Predefined macros within the 3.C language

__line__ Current line number

__file__ the current file name

__date__ Current date printf ("%s\n", __date__);

__time__ Current Time

__stdc__ whether the standard return value for C is 0 or 1

__stdc__? " In accordance with ":" Non-compliance "; printf ("%d\n", __stdc__);

#define QUANJU (x) g_# #x

int Quanju (i) = 20;

#define STR (x) #x

#define GLOBEL (x) g_# #x

int Globel (i) = 30;

int main ()

{

int i=20;

printf ("%s\n", STR (3));

printf ("%d\n", Globel (i));

}

Second, large-scale software development

1. Operation procedure

A. Original only one file main.c Input function output function declaration

B. Multi-person development to split the original file into three files, respectively, *.h, *.C, MAIN.C

C. When compiling

1) Compile the different source files separately, generate the corresponding target files gcc-c INPUT.C=>INPUT.O

2) Multiple target file links can be delivered to the same executable file

GCC INPUT.O main.o=>a.out

3) in the Main.c file, record the import header file

3. If you want to share global variables in a project, use the extern keyword to declare the variable in the file you are using, and you can get the value of the global variable.

4. You can add a static modifier before a global variable, which can only be used in the current file, and static may also modify the function. The static variable, which is a private variable, adds a static function, which is a private function.

Third, structural body

1. Format of the structure body

struct{

Members

} variable name;

typedef struct{

int age;//Member

Char name[20];

}student2;//aliases

2. Structure use:

Student2 stu = {, "Lisi"};

Stu.age = 18;

printf ("name:%s age:%d\n", stu.name,stu.age);

3. If the member in the struct is a string and cannot be assigned by =, use:

strcpy (Student2.name, "Zhangsan");

4. The definition of a struct is not memory-intensive, so the definition of the struct can be placed in the header file, and the type can be used by other files in the project.

5. If it is a basic data type, use a variable of struct type. A member that can manipulate the member.

6. Declare a variable of struct type, occupying space for the sum of the space occupied by all member types? Boundary alignment sizeof (STUDENT2)

7. If you assign a value using a struct variable, it is equivalent to assigning the value of each member in the struct to the member of the new struct variable.

Iv. United

1. The usage, syntax, and structure of the Union are very similar, but the memory allocated by all members of the Union is the same block. (Only one member information can be saved, and the combined space is the value of the maximum member space)

2. Union can use a piece of memory to correspond to multiple data types

3. Union and structure differences, structure can hold multiple member information, and the Union can only save one member information and the last one.

typedef Union {

int age;

Char name[2];

}lianhe;

V. Enumeration

1. Define an enumeration

Enum{spr,sum,aut,win};//0123

2. The default value of the enumeration starts at 0, and each value is an integral type constant

3. Modify the enumeration value only when declaring an enumeration

enum{spr,sum=2,aut,win};//0234

4. Modified enumeration value = Previous enumeration value plus 1

typedef Enum{spr,sum,aut,win} SEASON;

void Printseasonbynum (SEASON SEASON) {

Switch (season) {

Case spr:printf ("Spring!\n"); Break

Case sum:printf ("Summer!\n"); Break

Case aut:printf ("Autumn! \ n "); Break

Case win:printf ("Winter! \ n "); Break

}

}

Day12 Advanced Pointers

First, advanced pointers

1. Dynamic memory allocation for heap memory

The memory is divided into several parts:

Stack area variables

Code Area string

Global Zone Global Variables

Heap area (self-created, self-recycling, variable, string)

2. In order to allocate memory dynamically from the heap, specify a space for the number of bytes, return the first address, or NULL if the failure returns (null).

Contains the header file Stdlib.h, the basic memory operation is written well.

The 3.malloc function, which can allocate a specified number of bytes of space from the heap, returns the first address if the failure returns NULL.

The 4.calloc function will clear 0 of all bytes allocated before it is used. (Initialize)

5.realloc function, you can adjust the allocated space, there are two cases, if the current position can be adjusted in the original position adjustment, if the current position can not be adjusted, a new position.

The 6.free function is used to free (reclaim) space allocated from the heap (memory. )

Second, malloc function

1. Introduction of header File Stdlib.h

2. There is no variable name in the heap, only the data in memory (value) can be obtained by pointers.

3. When using heap memory pointers, it is best to use the const keyword modifier.

int* Const P = ...;

The 4.malloc function can allocate heap memory, in bytes, in size. malloc (sizeof (int) *)

The 5.if (point!=null) statement avoids memory allocation failures, causing program crashes and non-null (secure) authentication.

6. After the heap memory is used, be sure to release: free (point);

Three, calloc function

Parameter 1: Number of elements

Parameter 2: The amount of space each element occupies

When the Calloc function allocates memory, it does clear 0 operations.

int* Const P=MALLOC (sizeof (int));//Heap memory

int* Const P=CALLOC (3,sizeof (int));

if (p!=null) {

int i;

for (i=0;i<3;i++) {

scanf ("%d", p+i);

}

for (i=0;i<3;i++) {

printf ("%d\n", * (P+i));

}

}

Free (p);

Iv. realloc function to adjust memory space

1. Allocating space

Parameter 1 which space to adjust

Parameter 2 size after adjustment

ReAlloc (point, sizeof (int))

2. Possible situations

ReAlloc (NULL, 5*sizeof (int)), equivalent to malloc ()

ReAlloc (point, 0); equivalent to free ()

3. If the original position can adjust the space, the original position adjustment

4. If the original location is not able to adjust the space, the program will automatically create space in the new location, and move the original value to the new location, and automatically release the original space.

Five, function pointers

1. Use the pointer to store the address of the code area function, all functions are pointers, function names are function pointers.

2. Function pointers can be used to make parameters that can be passed in. The parameter type and return type of the function pointer are exactly the same. ->block

void Func () {

printf ("hello!");

}

int main () {

function pointers

printf ("%p\n", func);

printf ("%p\n", &func);

function pointer variable

void (*func_ptr) (void) =func;

Func_ptr ();

}

Liu, void*

1. Represents any type of pointer, malloc allocates heap memory, because the memory storage type cannot be determined, so you can use void* to represent arbitrary pointer types.

2. The void* pointer cannot be manipulated directly, and the type conversion can be performed before the * operation.

3.void* can add and subtract operations, but in 1 bytes for the operation, so that to the void to add, subtract operations, it is best to first convert the data type.

typedef enum{int,char,float,double} type;

void Func2 (void* p,type t) {

Switch (t) {

Case int:printf ("%d\n", * ((int*) p));

Case char:printf ("%c\n", * ((char*) p));

}

}

int main () {

int i=10;

Char j= ' A ';

Func2 (&i,int);

Func2 (&j,char);

}

The first part object-c fundamental

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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