gpt4 book ai didi

c++ - 未处理的异常访问冲突写入位置 0xCDCDCDCD - 在结构 C++ 中

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:27 25 4
gpt4 key购买 nike

我创建了一个结构指针。并为其赋值。我试图打印分配给它的值。它提示未处理的异常访问冲突写入位置 0xCDCDCDCD。这样做有什么问题?如何无一异常(exception)地完成这个任务?

StructCol.h

#include "stdafx.h"
#ifndef StructCol_H
#define StructCol_H

#include<string>

using namespace std;

struct ABC
{
string test;
int no;

void print()
{
cout << test << endl;
cout << no << endl;
}
};

#endif

StructTest2.cpp

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<stdio.h>
#include "StructCol.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
ABC*abc = (ABC*)malloc(sizeof(ABC));
abc->no = 47;
abc->test = "fyp";
abc->print();
//delete abc;
//abc->print();

_getch();
return 0;
}

最佳答案

您的结构包含一个 std::string 元素。这是一种需要在创建该对象时执行其构造函数的类型。

您不能使用 malloc 创建结构,因为 C 函数不知道构造函数。

C++ newdelete 表达式会做正确的事情。当然,您应该更喜欢使用智能指针而不是手动内存管理(或者根本没有动态分配)。

修复代码的快速方法是使用newdelete:

ABC *abc = new ABC;
...
delete abc;

关于c++ - 未处理的异常访问冲突写入位置 0xCDCDCDCD - 在结构 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com