[C language/C++ implementation structure and pointer detailed tutorial]

Structures and Pointers

structure

A structure in C language is a custom data type that allows us to combine different types of data to form a new data type. Structures can contain different types of data, such as integers, characters, floating-point numbers, arrays, etc., and can be used to describe complex data structures. The structure in the C language will be introduced in detail below, including the definition of the structure, the declaration and initialization of the structure variable, and the access of the structure members.

1. Definition of structure

The definition of the structure uses the keyword struct , and its syntax is as follows:

struct structure name {
data type member name 1;
data type member name 2;
data type member name 3;
...
};

Among them, the structure name is our custom name, the member name is the name we name each element in the structure, and the data type can be any C language data type or other structure types.

For example, we can define a structure to represent a student's information, including name, age, gender, student number and grades, etc. The code is as follows:

struct Student {
    
    
    char name[20];
    int age;
    char sex;
    char id[10];
    float score;
};

In the above code, we define a structure called Student, which contains 5 members, namely name, age, gender, student number and grade, and their data types are char, int, char, char and float.

2. Declaration and initialization of structure variables

Once the structure is defined, we can declare structure variables and initialize them. There are two ways to declare and initialize structure variables, namely:

1. Declare first and then initialize

struct Student stu;
stu.age = 18;
strcpy(stu.name, "Tom");
stu.sex = 'M';
strcpy(stu.id, "2018001");
stu.score = 95.0;

In the above code, we first declare a structure variable named stu of the Student type, and then initialize its members.

2. Simultaneous declaration and initialization

struct Student stu = {
    
    "Tom", 18, 'M', "2018001", 95.0};

In the above code, we initialize the stu structure variable while declaring it, and the order of initialization is consistent with the order of member definition.

3. Access to structure members

Access to structure members uses the " . " operator, for example:

printf("姓名:%s\n", stu.name);
printf("年龄:%d\n", stu.age);
printf("性别:%c\n", stu.sex);
printf("学号:%s\n", stu.id);
printf("成绩:%f\n", stu.score);

In the above code, we use the "." operator to access each member of the stu structure variable, and then output their values.

Fourth, the structure as a function parameter

Structs can be used as parameters of functions, for example:

void printStudent(struct Student s) {
    
    
    printf("姓名:%s\n", s.name);
    printf("年龄:%d\n", s.age);
    printf("性别:%c\n", s.sex);
    printf("学号:%s\n", s.id);
    printf("成绩:%f\n", s.score);
}

In the above code, we define a function called printStudent, whose parameter is a structure variable s of Student type, and then output the members of the s variable.

Five, complete code

The following is a complete example of using a structure, which defines a structure named Student, declares a structure variable named stu, initializes it, and finally outputs the members of the stu variable .

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

struct Student {
    
    
    char name[20];
    int age;
    char sex;
    char id[10];
    float score;
};

void printStudent(struct Student s) {
    
    
    printf("姓名:%s\n", s.name);
    printf("年龄:%d\n", s.age);
    printf("性别:%c\n", s.sex);
    printf("学号:%s\n", s.id);
    printf("成绩:%f\n", s.score);
}

int main() {
    
    
    struct Student stu = {
    
    "Tom", 18, 'M', "2018001", 95.0};
    printStudent(stu);
    return 0;
}

The result of the operation is as follows:

姓名:Tom
年龄:18
性别:M
学号:2018001
成绩:95.000000

6. Summary

This article introduces the structure in C language, including the definition of the structure, the declaration and initialization of the structure variable, the access of the structure members and the structure as a function parameter, etc. Structure is a very important data type, which can be used to describe complex data structures, which is convenient for program writing and maintenance.

pointer

Pointer is a very important concept in C language, and it is also one of the most difficult concepts for beginners to understand. The essence of a pointer is an address, which points to a location where data is stored. Through the pointer, we can access and manipulate the data stored in this location. The following will explain in detail the related concepts and usage of pointers in C language, with detailed code and code explanation.

1. Definition of pointer

The definition format of the pointer is: * data type pointer variable name ; wherein, the data type indicates the data type pointed to by the pointer, and the pointer variable name is an identifier used to indicate the position of the pointer variable in the memory. For example:

int *p; //定义一个指向整型数据的指针变量

When defining a pointer variable, it is necessary to specify the data type pointed to by the pointer. This is because different data types occupy different sizes of storage space, and pointers need to know the size of the data type they point to in order to perform pointer operations correctly.

Second, the initialization of the pointer

The pointer variable does not automatically point to a certain address when it is defined, and needs to be initialized to point the pointer variable to a legal memory address. Pointer variables can be initialized in the following ways:

① Direct assignment: Assign the pointer variable to a known address.

int a = 10;
int *p = &a; //将指针p指向变量a的地址

② Dynamically allocate memory through the malloc function:

int *p = (int *)malloc(sizeof(int)); //动态分配一个整型数据的内存空间,并将指针p指向这个空间的地址

③ Initialize by function return value:

int *get_array(int size) {
    
    
    int *p = (int *)malloc(size * sizeof(int));
    return p;
}

int *arr = get_array(10); //将指针arr指向动态分配的数组的首地址

Three, pointer operation

Pointer variables can be added and subtracted, and the pointed address will be offset accordingly according to the result of the operation. For example:

int a[5] = {
    
    1, 2, 3, 4, 5};
int *p = a; //将指针p指向数组a的首地址

for (int i = 0; i < 5; i++) {
    
    
    printf("%d ", *p); //输出指针p所指向的数据
    p++; //指针p指向下一个数据
}

In the above code, the pointer p first points to the first address of the array a, and then accesses each element in the array in turn through pointer arithmetic, and outputs their values.

Pointer variables can also perform comparison operations, comparing whether the addresses they point to are the same. For example:

int a = 10, b = 20;
int *p1 = &a, *p2 = &b;

if (p1 > p2) {
    
    
    printf("p1指向的地址大于p2\n");
} else {
    
    
    printf("p1指向的地址小于等于p2\n");
}

In the above code, through the comparison of the pointer variables p1 and p2, the size of the address they point to is judged, and the corresponding result is output.

Fourth, the application of the pointer

Pointers are widely used in C language and can be used in the following aspects:

① Dynamic memory allocation: The memory space can be dynamically allocated through the pointer and malloc function, avoiding the problem of memory waste during static allocation.

② Function parameter passing: function parameters can be passed through pointers, and the calculation results inside the function can be returned to the caller.

void swap(int *x, int *y) {
    
    
    int temp = *x;
    *x = *y;
    *y = temp;
}

int a = 10, b = 20;
swap(&a, &b); //将变量a和b的值交换

In the above code, the function of the function is realized by exchanging the values ​​of the variables a and b through the pointer.

③ Array access: The array name is essentially a pointer to the first address of the array, and each element in the array can be accessed through the pointer.

int a[5] = {
    
    1, 2, 3, 4, 5};
int *p = a; //将指针p指向数组a的首地址

for (int i = 0; i < 5; i++) {
    
    
    printf("%d ", *(p + i)); //输出数组中的每个元素
}

In the above code, each element in the array a is accessed through the pointer p, and their values ​​are output.

5. Precautions for pointers

Pointers need to pay attention to the following points when using:

① Pointer variables must be initialized before they can be used.

② Pointer variables cannot access unallocated memory space, otherwise the program will crash.

③ The pointer variable must point to the correct data type, otherwise it will cause a pointer operation error.

④ When using pointer variables, you need to pay attention to the boundary problem of pointer arithmetic to avoid out-of-bounds access.

6. Example code

The following is a complete sample code that demonstrates the definition, initialization, operation and application of pointers:

#include <stdio.h>
#include <stdlib.h>

void swap(int *x, int *y) {
    
    
    int temp = *x;
    *x = *y;
    *y = temp;
}

int *get_array(int size) {
    
    
    int *p = (int *)malloc(size * sizeof(int));
    return p;
}

int main() {
    
    
    int a = 10, b = 20;
    int *p1 = &a, *p2 = &b;
if (p1 > p2) {
    
    
    printf("p1指向的地址大于p2\n");
} else {
    
    
    printf("p1指向的地址小于等于p2\n");
}

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

for (int i = 0; i < 5; i++) {
    
    
    printf("%d ", *(p + i));
}
printf("\n");

int *arr2 = get_array(10);
for (int i = 0; i < 10; i++) {
    
    
    *(arr2 + i) = i;
    printf("%d ", *(arr2 + i));
}
printf("\n");

swap(&a, &b);
printf("a=%d, b=%d\n", a, b);

free(arr2);

return 0;
}

In the above code, two pointer variables p1 and p2 are defined, and the corresponding results are output by comparing the sizes of the addresses they point to. Then an array arr is defined, each element in the array is accessed through the pointer variable p, and their values ​​are output. Then an array is dynamically allocated through the function get_array, each element in the array is accessed through the pointer variable arr2, and their values ​​are output. Finally, the values ​​of variables a and b are exchanged through the function swap, and their values ​​are output. Note that after using the dynamically allocated array, you need to use the free function to release the memory space.

7. Summary

This article explains in detail the related concepts and usage of pointers in C language, including the definition, initialization, operation and application of pointers. Pointers are widely used in C language, and can be used for dynamic memory allocation, function parameter passing, array access, etc. When using pointers, you need to pay attention to the initialization of pointer variables, the data type pointed to, boundary issues, etc. Through the study of this article, I believe that readers have a deeper understanding of the pointer's understanding and application ability.

Guess you like

Origin blog.csdn.net/qq_43884946/article/details/131276067