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