weixin_43361584 2021-06-05 14:27 采纳率: 100%
浏览 33
已采纳

c++结构体申请内存空间出现问题 有可能是string的问题

#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;	//结构体

typedef struct student {
	int score;
	string id;
	string name;
}stu,*stu1;


int main()
{
	/*stu s;
	s.name = "weilifeng";
	s.id = "201743303117";
	s.score = 60;
	cout << s.name << " " << s.id << " " << s.score << endl;*/ 
    //上面注释的代码可以运行



    //我想通过指针申请内存空间 ,然后再进行赋值,不报错,但运行不了
    //我大概觉得可能是越界的问题。但是问题出在哪里不知道  求解答
	stu1 a;
	a = (stu1)malloc(sizeof(stu));
	if (a == NULL) 
	{
		cout << "error";
		exit(0);
	}
	a->score = 60;
	a->id = "201743303117";
	a->name = "weilifeng";
	cout << a->name << " " << a->id << " " << a->score << endl;
}

通过断点,调试出来的问题   出现在 这句

a->id = "201743303117";

下面是报错的反馈

0x00007FFB517113D6 (vcruntime140d.dll)处(位于 Project1.exe 中)引发的异常: 0xC0000005: 读取位置 0xFFFFFFFFFFFFFFFF 时发生访问冲突。


 

  • 写回答

4条回答 默认 最新

  • CSDN专家-link 2021-06-05 18:04
    关注

    把a = (stu1)malloc(sizeof(stu));改为a = new stu;就可以了。malloc只是分配内存,sizeof无法计算string的内存大小,不能分配有效空间。

    #include<iostream>
    #include<string>
    #include<stdio.h>
    using namespace std;	//结构体
    typedef struct student {
    	int score;
    	string id;
    	string name;
    }stu,*stu1;
     
    int main()
    {
    	stu1 a = new stu;
    	if (a == NULL) 
    	{
    		cout << "error";
    		exit(0);
    	}
    	a->score = 60;
    	a->id = "201743303117";
    	a->name = "weilifeng";
    	cout << a->name << " " << a->id << " " << a->score << endl;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度