Defining and using a pointer in the C language and Array

Pointer Features

  • He is an address memory
  • Arithmetic pointer itself
  • The pointer points to the content being operable

How is the operating system memory management

Stack space

  • Size of 4M ~ 8m
  • When entering the function will be push data

Heap space

  • 1g 4g size of the operating system
  • Global Variables

Memory map

  • You can modify the contents of the hard disk to modify the contents of memory
  • Generally frequently used in the database

Allocation and deallocation of memory

  • C language method to allocate memory

    //  malloc(需要分配的大小); 这里的分配的大小需要对齐的2的指数
    void *mem = malloc(size);
  • Release memory

    // 一般分配的内容都是在堆空间中的
    // 如果使用完不去释放会照成内存泄漏和野指针的出现
    free(men);
  • What is a memory leak:
    • Continue to apply to the system memory
    • Memory applications do not go release
    • And definitely not a memory leak
  • What is the field guide
    • The pointer has been freed up
    • Someone else has created the pointer
    • Over the past but it uses the pointer

Function pointer

Return Value (* pointer variable name) (parameter list);

int func(int x); // 声明一个函数
int (*f)(int x); // 声明一个函数指针
f = func; // 将func函数的首地址赋值给指针f
#include <stdio.h>

int sum (int a, int b)
{
    return (a+b);
}

int main(int argc, int *argv[])
{
    // 定义一个函数指针 
    int (*f) (int, int);
    // f 指向 sum函数
    f = sum;
    // 执行f函数,相当于执行sum函数
  int f_sum = f(2,3);
    printf("f_sum: %d\n", f_sum);
  
  return 0;
}

Pointer is the memory address: void *, char *

The array is: char c [2], int arr [10], the same type refers to a continuous space

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

int main(int argc, char *argv[])
{
    // 定义两个int类型的指针
    int *a, *b;
    // 通过malloc在堆里面开辟了空间
    a = (int*)malloc(sizeof(int));
    b = (int*)malloc(sizeof(int));
    *a = 1;
    *b = 2;
    // 指针a的地址是&a, a是指向空间的地址,*a是指向空间的值
    printf("addr of a:%p, %p, %d\n", &a, a, *a);
    printf("addr of b:%p, %p, %d\n", &b, b, *b);
    return 0;
}

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

int main(int argc, char *argv[])
{
    // 创建一个数组c里面有3个数据,int类型的数组一个数组占4个字节,地址相关的空间相差是1个字节
    int c[3] = {1,2,3};
    printf("c的地址:%p\t%p\tc[0]:%p\tc[1]:%p\tc[2]:%p\t\n",c, &c,  &c[0], &c[1], &c[2]);
    printf("%d, %d, %d\n", c[0], c[1], c[2]);
}

Guess you like

Origin www.cnblogs.com/fandx/p/12122863.html