c++ 使用malloc分配对象数组*

#include <malloc.h>
#include <stdio.h>

#include <iostream>
#include <string>

class Student {
   public:
    int id;
    std::string name;
};

int main(int argc, char const* argv[]) {
    int size = 10;
    Student* st = (Student*)malloc(sizeof(Student) * size);
    for (Student* i = st; i < st + size; i++) {
        i->id = 123;
        i->name = "qiumc";
    }

    // 使用下标获取到的是具体元素,而不是指向具体元素的指针
    std::cout << st[0].name << std::endl;
    // 如果要释放st内存,仅仅需要free(st);既可以,不能把st当做一个数组,进行逐个释放。
    free(st);
    return 0;
}
posted @ 2021-10-25 09:51  邱明成  阅读(501)  评论(0编辑  收藏  举报