内存分配

基本类型 / 指针

//指向 int 值的指针
int *pInt = malloc(sizeof *pInt);
//没有内存时 malloc 返回 nullptr
if (pInt == nullptr) {
    return 1;
}
*pInt = 50;

//指向 double 的指针
double *pDouble = malloc(sizeof *pDouble);
if (pDouble == nullptr) {
    free(pInt);
    return 1;
}
double d = 3.14;
*pDouble = d;
//*pInt is 50
//*pDouble is 3.14

printf("*pInt is %d\n", *pInt);
printf("*pDouble is %g\n", *pDouble);

//释放内存:free 之后不得再读取该值
free(pInt);
free(pDouble);