内存分配

基本类型 / 指针

//pointer to int value
int *pInt = malloc(sizeof *pInt);
//malloc returns nullptr when there is no memory
if (pInt == nullptr) {
    return 1;
}
*pInt = 50;

//pointer to 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);

//Memory release: after free the value must not be read
free(pInt);
free(pDouble);