C++动态分配分配内存空间

动态分配存储空间的方法:

#include 

// 申请size个字节的连续空间
void *malloc(size_t size);
// 申请n个size个字节的连续空间
void *calloc(size_t n, size_t size);
// 重置ptr为,指向size个字节的连续空间。
// (注:若ptr原指向内存长度,大于size,则ptr不变。若小于size,则ptr可能会变化)
void *realloc(void *ptr, size_t size);
// 释放内存
void free(void *ptr);

代码:

#include 
#include 

typedef struct _STUDENT_{
        char name[20];
        int score;
}STUDENT;

int main()
{
        printf("use malloc\n");
        STUDENT * a = (STUDENT*)malloc(sizeof(STUDENT));
        sprintf(a->name, "%s", "ming");
        a->score = 81;
        printf("student name:%s, score:%d\n", a->name, a->score);
        free(a);

        printf("use calloc\n");
        STUDENT * b = (STUDENT*)calloc(1, sizeof(STUDENT));
        sprintf(b->name, "%s", "ting");
        b->score = 95;
        printf("student name:%s, score:%d\n", b->name, b->score);
        free(b);
        return 0;
}

输出:

[root@localhost test]# ls
main.cpp
[root@localhost test]# g++ -o demo main.cpp 
[root@localhost test]# ls
demo  main.cpp
[root@localhost test]# ./demo 
use malloc
student name:ming, score:81
use calloc
student name:ting, score:95
[root@localhost test]# 

你可能感兴趣的:(c++)