小程序反应大问题

来源:互联网 发布:重庆网络主管招聘 编辑:程序博客网 时间:2024/05/16 19:00

C++中的new。
new int;//开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针)   
new int(100);//开辟一个存放整数的空间,并指定该整数的初值为100,返回一个指向该存储空间的地址   
new char[10];//开辟一个存放字符数组(包括10个元素)的空间,返回首元素的地址   
new int[5][4];//开辟一个存放二维整型数组(大小为5*4)的空间,返回首元素的地址   
float *p=new float (3.14159);//开辟一个存放单精度数的空间,并指定该实数的初值为//3.14159,将返回的该空间的地址赋给指针变量p   
new运算符使用的一般格式为   new 类型 [初值]   用new分配数组空间时不能指定初值。如果由于内存不足等原因而无法正常分配空间,则new会返回一个空指针NULL,用户可以根据该指针的值判断分配空间是否成功。  
delete运算符使用的一般格式为   delete [ ] 指针变量   
例如要撤销上面用new开辟的存放单精度数的空间(上面第5个例子),应该用   delete p;   
前面用“new char[10];”开辟的字符数组空间,如果把new返回的指针赋给了指针变量pt,则应该用以下形式的delete运算符撤销该空间:   
delete [] pt;//在指针变量前面加一对方括号,表示是对数组空间的操作   

开辟空间以存放一个结构体变量。

#include "stdafx.h"#include <iostream>#include <string>using namespace std;struct Student{    string name;    int num;    char sex;};int main(){    Student *p;    // p = new Student;    p->name = "Wang Fun";    p->num = 10123;    p->sex = 'm';    cout << p->name << endl << p->num << endl << p->sex << endl;    delete p;    return 0;}

以上程序所报错误为: error C4700: 使用了未初始化的局部变量“p”;

#include "stdafx.h"#include <iostream>#include <string>using namespace std;struct Student{    string name;    int num;    char sex;};int main(){    Student *p=NULL;    // p = new Student;    p->name = "Wang Fun";    p->num = 10123;    p->sex = 'm';    cout << p->name << endl << p->num << endl << p->sex << endl;    delete p;    return 0;}

以上程序所报错误(此错误为指针在debug下定义为NULL时报的错)为:
这里写图片描述

正确代码如下:

#include "stdafx.h"#include <iostream>#include <string>using namespace std;struct Student{    string name;    int num;    char sex;};int main(){    Student *p;    p = new Student;    p->name = "Wang Fun";    p->num = 10123;    p->sex = 'm';    cout << p->name << endl << p->num << endl << p->sex << endl;    delete p;    return 0;}
0 0
原创粉丝点击