我刚开始学习c ++。我遇到了结构问题。当我在尝试将字符串添加到结构时向结构程序beaks添加数据时。我真的不知道问题出在哪里。这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
typedef struct hardware
{
int id; // will store information
string name;
int year;
float price;
hardware *next; // the reference to the next hardware
};
hardware *head = NULL; //empty linked list
int tempid = 0,tempyear=0, hardware_number = 0, counter = 0;
string tempname="";
float tempprice=0;
cout<<"Unesite sifru proizvoda:";
cin>>tempid;
cout<<"Unesite naziv proizvoda:";
cin>>tempname;
cout<<"Unesite godinu proizvoda:";
cin>>tempyear;
cout<<"Unesite cijenu proizvoda:";
cin>>tempprice;
cout<<"Unijeli ste : ID: "<<tempid<<", naziv: "<<tempname<<", godina: "<<tempyear<<", cijena: "<<tempprice<<", hardware No: "
<<++counter;
hardware *temp;
temp = (hardware*)malloc(sizeof(hardware));
temp->id = tempid;
temp->name = tempname;
temp->year = tempyear;
temp->price = tempprice;
temp->next = head;
head = temp;
return 0;
编辑1: 当我运行程序时它编译得很好。输入数据后,将在此行填写结构(id,名称,价格,年份......)程序中断
temp->name = tempname;
这是错误输出:
An unhandled exception of type 'System.AccessViolationException' occurred in proba.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
答案 0 :(得分:2)
使用temp = new hardware;
代替temp = (hardware*)malloc(sizeof(hardware));
来确保调用构造函数。
答案 1 :(得分:0)
temp->name
,因此您无法在赋值运算符的左侧使用它。如果您认为自己构建了它,请指向您认为构造它的代码行。我打赌你不能。 (你为它分配了内存,但你从来没有在那个内存中构造过一个字符串!)
答案 2 :(得分:0)
使用new()而不是malloc()来构造类。 在这种情况下,永远不会调用std :: string的构造函数!
如果你是C ++的初学者,我建议你现在总是使用new / delete,而不是malloc / free。