#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
struct stud
{
int num;
char *name;
char sex;
float score;
}*ps;
ps=(struct stud *)malloc(sizeof (struct stud));
ps->num=102;
ps->name="Zhang Hua";
ps->sex='f';
ps->score=72.5;
cout<<"Number="<<ps->num<<",Name="<<ps->name<<endl;
cout<<"Sex="<<ps->sex<<",Score="<<ps->score<<endl;
free(ps);
return 0;
}
动态存储分配函数calloc使用示例:
int *pi;
double *pd;
pi=(int *)calloc (10,sizeof(int));
pd=(double *)calloc(20,sizeof(double));
当程序执行到一定时候,需要释放所有分配的动态内存时,可以写:
free(pi);
free(pd);
动态存储分配和释放运算符new和delete
为更为方便地实现动态内存分配与释放,C++语言提供了两和运算符new和delete。它们都是C++关键字。使用运算符new可为动态数据申请分配堆内存。而使用delete可以释放原先由new所申请的堆内存。
下述C++程序使用运算符new和delete实现内存分配与释放:
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
int main()
{
struct students
{
int num;
char name[15];
char sex;
float score;
};
students *ps;
ps=new students;
ps->num=102;
strcpy(ps->name,"Zhang Hua");
ps->sex='f';
ps->score=72.5;
cout<<"Number:"<<ps->num<<'/n';
cout<<"Name:"<<ps->name<<'/n';
cout<<"Sex:"<<ps->sex<<'/n';
cout<<"Score:"<<ps->score<<endl;
delete ps;
return 0;
}
终于敲完了,又一份C++学习笔记^_^