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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM