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 时发生访问冲突。


 

把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;
}

可以尝试用new运算符申请堆区空间

#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 =&s;
	if (a == NULL) 
	{
		cout << "error";
		exit(0);
	}
	a->score = 60;
	a->id = "201743303117";
	a->name = "weilifeng";
	cout << a->name << " " << a->id << " " << a->score << endl;
}

代码调整如上,已经能正常运行。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632