开发者社区> 问答> 正文

c++在函数中new的对象数组如何在主函数中使用

Student *p;
int main(){
read();
p[0].getname(); //这一行去掉正常运行,写在read()里也正常
delete[] p;
return 0;
}
int read(){
int n;
string str;
ifstream fin("k.txt");
fin>>n;
p=new Student[n];
for(int i=0;i {
fin>>str>>p[i].number>>p[i].name;
for(int j=0;j fin>>p[i].score[j];
}
fin.close();
return n;
}

这样会出现提示
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
如果在主函数里去掉 p[0].getname(); 就不会报错
把p[0].getname();写在read里也没有问题

展开
收起
a123456678 2016-03-06 09:39:41 3520 0
1 条回答
写回答
取消 提交回答
  • Student *p;申明的是一个结构体指针, 必须给这个指针开辟内存 p= new Student() 多说无益 上图
    screenshot
    如果是多个学生 Student
    一个学生:

    #include "stdafx.h"
    #include "iostream"
    using namespace std;
    struct Student
    {
    char name;
    int age;
    
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    Student *p;
    p = new Student;
    p->name = 'a';
    p->age = 10;
    cout <<"学生姓名: "<< p->name << endl;
    getchar();
    return 0;
    }
    
    多个学生:
    #include "stdafx.h"
    #include "iostream"
    using namespace std;
    struct Student
    {
    char name;
    int age;
    
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    Student *p;
    p = new Student[2];
    p->name = 'a';
    p->age = 10;
    (p+1)->name = 'b';
    (p+1)->age = 12;
    cout <<"学生姓名: "<< p->name <<" 年龄:"<<(p)->age<< endl;
    cout << "学生姓名2: " << (p + 1)->name << " 年龄:"<<(p + 1)->age<<endl;
    getchar();
    return 0;
    }
    2019-07-17 18:54:01
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载