1. 程式人生 > >c++:動態記憶體分配(new和delete的使用)

c++:動態記憶體分配(new和delete的使用)

//============================================================================
// Name        : c++動態記憶體分配.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

struct Student
{
	int num;
	string name;
	char sex;
};

int main()
{
	Student *p;//定義一個指向結構體的指標
	p = new Student;//和c語言中的malloc函式的功能是相似的,動態的開闢一段記憶體空間
	p->name = "wang fun";
	p->num = 10123;
	p->sex = 'm';
	cout<<p->name<<endl;
	cout<<p->num<<endl;
	cout<<p->sex<<endl;

	delete p;//如果是陣列的話,形式為delete []p;

	return 0;
}

執行結果: