我刚开始学习c++。我遇到了结构问题。当我将数据添加到结构程序喙时,它会尝试将字符串添加到结构中。真不知道哪里出了问题。这是我的代码:
#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.