C language basic syntax - pointer

  1. What is a pointer

  2. Pointers are used for parameters

  3. Pointers are used to return values

  4. Pointer addition and subtraction operations

  5. Difference between pointer and array

 

1. What is a pointer

  • Memory is divided into bytes, each byte has a unique address, and the pointer points to the memory address.

  • A variable that holds a pointer is called a pointer variable. (save address)

  • declare a pointer variable

int i = 0;

int* p;//declare a pointer variable int* pointer type

int * p; int* p; int *p;

  • Each pointer variable can point to a specific type of object (address, memory area).

  • The pointer is a reference data type, because it does not save the data itself, but only saves the address of the data, and indirectly finds the data in the memory.

 

2. Pointers are used for parameters

  • pass by value

void swap(int a, int b) {

  int temp = a;
  a = b;
  b = temp;

}

int main() {
  int a = 5, b = 8;

  swap(a, b);

  printf(“%d,%d”, a, b);

}

  • Address delivery

void swap(int *a, int *b) {

  int temp = *a;
  *a = *b;
  *b = temp;

}

int main() {
  int a = 5, b = 8;

  swap(&a, &b);

  printf(“%d,%d”, a, b);

}

 

3. Pointers are used to return values

  • Pointers can also be used as return values

  • Do not return the address of an automatic variable, because of the life cycle of a local variable, when the function ends, the local variable will be automatically cleared (released). Solution: Extend the life cycle.

 

4. Pointer addition and subtraction operations

  • Pointers support adding integers, subtracting integers, and comparing and subtracting pointers, but the unit of operation is determined by the type of the pointer.

    int type pointer + 1 = address + 4

    char type pointer + 1 = address + 1

  

5. Difference between pointer and array

  • Takes up memory space

-Array occupied space = space occupied by array elements * length

- Space occupied by pointers = 8 bytes in 64-bit systems, fixed, regardless of the type of pointer.

  • Assignment

- The array name is a constant, its value cannot be modified

- Pointers are variables and can be assigned multiple times

- Assignment to a pointer, which is essentially a change to what the pointer points to

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324895425&siteId=291194637