Brother Jiang takes you to play with C language | 13 - one level pointer and multi-level pointer

Basic concepts of pointer

  • What is the address

    • Address in life:
    • Memory address:
  • Address and data in memory unit are two completely different concepts

    • The address is like the room number. According to this number, we can find the corresponding room
    • Memory units are like rooms, which are dedicated to storing data
  • Variable address:

    • The starting address of the memory unit allocated by the system to the variable
int num = 6; // Occupy 4 bytes
//Then the address of the variable num is: 0ff06

char c = 'a'; // Occupy 1 byte
//Then the address of variable c is 0ff05

What is a pointer

  • In the computer, all data are stored in memory cells, and each memory cell has a corresponding address. As long as this address is used, the data stored in the corresponding cell can be found

  • Since the required variable unit can be found through the address, we say that the address points to the variable unit. Visualized addresses are called "pointers"

  • The pointer (address) of the memory unit and the content of the memory unit are two different concepts.

What is a pointer variable

  • In C language, it is allowed to use a variable to store the addresses of other variables. This kind of variable specially used to store the addresses of other variables is called pointer variable

  • Example:

    int age;// Define a common variable
    num = 10;
    int *pnAge; // Define a pointer variable
    pnAge = &age;

Defines the format of pointer variables

  • The definition of pointer variable includes two contents:
    • Pointer type description, that is to define the variable as a pointer variable;
    • Pointer variable name;
  • Example:
char ch = 'a';
char *p; // A pointer to a character variable
p = &ch;  
int num = 666;
int *q; // A pointer to an integer variable
q = #  
  • Where, * indicates that this is a pointer variable
  • The variable name is the defined pointer variable name
  • The type specifier indicates the data type of the variable pointed to by this pointer variable

Initialization method of pointer variable

  • There are two methods of initializing pointer variables: initializing while defining and initializing after defining
    • Initialize while defining
int a = 5;
int *p = &a;
    • Define before initialize
int a = 5;
int *p;
p=&a;
    • Initialize pointer to NULL
int *p=NULL;
int *q=0;
  • Illegal initialization:
    • Pointer variables can only store addresses and cannot store other types
int *p;
p =  250; // Wrong writing
    • When assigning a value to a pointer variable, you cannot add "*" before the pointer variable
int *p;
*p=&a; //Wrong writing
  • Note:

    • Multiple pointer variables can point to the same address
  • The direction of the pointer can be changed

int a = 5;
int *p = &a;
int b = 10;
p = &b; // Modify pointer pointing
  • The pointer is uninitialized and contains a garbage value. At this time, we are a wild pointer
    • Wild pointers can cause the program to crash
    • Wild pointer access you shouldn't access data
    • Therefore, the pointer must be initialized to access the storage area it points to

Access the storage space pointed to by the pointer

  • The address operator & is provided in C language to represent the address of variables. Its general form is:
    • &Variable name;
  • C language provides * to define pointer variables and access the memory storage space pointed to by pointer variables
    • When defining a variable, * is a type specifier, indicating that the defined variable is a pointer variable
int *p=NULL; // Define pointer variables
    • When a variable is not defined, * is an operator representing the storage space pointed to by the access pointer
int a = 5;
int *p = &a;
printf("a = %d", *p); // Access pointer variable

Pointer type

  • In the same compiler environment, the memory space occupied by a pointer variable is fixed.

  • Although all pointers occupy the same memory space in the same compiler, different types of variables occupy different bytes

    • An int occupies 4 bytes, a char occupies 1 byte, and a double occupies 8 bytes;
    • Now there is only one address. How can I know how many bytes of storage space to access backward from this address? Is it 4, 1 or 8.
    • Therefore, the pointer variable needs the data type it points to to to tell it how many bytes of storage space to access

Secondary pointer

  • If a pointer variable stores the address of another pointer variable, the pointer variable is called the pointer variable pointing to the pointer. Also known as "secondary pointer"
    char c = 'a';
    char *cp;
    cp = &c;
    char **cp2;
    cp2 = &cp;
    printf("c = %c", **cp2);

  • Value rules of multi-level pointers
int ***m1;  //Value * * * m1
int *****m2; //Value: **** m2

practice

  • Define a function to exchange the values of two variables
  • Write a function that returns the sum and difference of two numbers at the same time

##Concept and definition of array pointer

  • Array element pointer
    • A variable has an address. An array contains several elements. Each array element also has a corresponding address. Pointer variables can also save the address of array elements
    • As long as a pointer variable holds the address of an array element, we call it an array element pointer
    printf("%p %p", &(a[0]), a); //Output result: 0x1100, 0x1100
  • Note: the array name a does not represent the entire array, but only the address of the first element of the array.
  • “p=a;” The function of is to "assign the address of the first element of array a to the pointer variable p", rather than "assign the value of each element of array a to P"

Pointer to access array elements

    int main (void)
{
      int a[5] = {2, 4, 6, 8, 22};
      int *p;
      // p = &(a[0]); 
      p = a;
      printf("%d %d\n",a[0],*p); // Output result: 2, 2
}

  • When the pointer points to an array element, the following operations are allowed:
    • Add an integer (with + or + =), such as p+1
    • Subtract an integer (with - or - =), such as p-1
    • Self addition operation, such as P + +, + P
    • Self subtraction operation, such as p –, -- p

  • If the pointer variable p points to an element in the array, p+1 points to the next element in the same array and p-1 points to the previous element in the same array.
  • Conclusion: there are two ways to access array elements:
    • Subscript method, such as a[i] form
    • Pointer method, * (p+i) form

  • be careful:
    • Although the array name is the first address of the array, the first address of the array saved by the array name cannot be changed
    int x[10];
	x++;  //error
	int* p = x;
	p++; //correct

Pointer and string

  • There are two ways to define strings
    • Character array
char string[]="I love lnj!";
printf("%s\n",string);
    • The string pointer points to a string
// The array name saves the address of the 0th element of the array, and the pointer can also save the address of the 0th element
char *str = "abc"

  • Precautions for using string pointer
    • You can view each character of the string
har *str = "lnj";
for(int i = 0; i < strlen(str);i++)
{
  printf("%c-", *(str+i)); // Output result: l-n-j
}
    • The string content cannot be modified
//   +The string saved by character array is saved in the stack. The things in the stack are readable and writable. All the characters in the string can be modified
//   +The character pointer is used to save the string. It saves the constant address of the string. The constant area is read-only, so we can't modify the characters in the string
char *str = "lnj";
*(str+2) = 'y'; // error
    • Cannot receive keyboard input directly
// The reason for the error is: str is a wild pointer, which does not point to a certain memory space
// So it is not allowed to write like this. If you allocate memory space to str, you can use it like this
char *str;
scanf("%s", str);

Pointer to function

  • Why can a pointer point to a function?
    • As a program, function also occupies part of the storage space in memory, and it also has a starting address
    • The function has its own address, so it's easy to do. Our pointer variable is used to store the address.
    • Therefore, a pointer can be used to point to a function. The function name represents the address of the function.
  • Definition of pointer function
    • Format: return value type (* pointer variable name) (formal parameter 1, formal parameter 2,...);
    int sum(int a,int b)
    {
        return a + b;
    }

    int (*p)(int,int);
    p = sum;
  • Pointer function definition skills

    • 1. Copy the function header you want to point to
    • 2. Enclose the function name in parentheses
    • 3. Precede the function name with a*
    • 4. Modify function name
  • Application scenario

    • Call function
    • Pass functions as parameters between functions
  • Note:

    • Since such pointer variables store the entry address of a function, it is meaningless to add and subtract them (such as p + +)
    • The parentheses on both sides of "(pointer variable name)" in a function call cannot be less. The parentheses in it should not be understood as evaluation operation. Here, it is just a symbol

If you think the article is helpful to you, like, collect, pay attention to, comment, and support four times with one button, your support is the driving force for brother Jiang's continuous update.

Supporting video address

Keywords: C C++ Programming Programmer pointer

Added by fhil85 on Mon, 31 Jan 2022 23:26:51 +0200