c++ - 尝试将字符串添加到结构时程序中断

标签 c++ string data-structures

我刚刚开始学习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.

最佳答案

使用 temp = new hardware; 而不是 temp = (hardware*)malloc(sizeof(hardware)); 确保调用构造函数。

关于c++ - 尝试将字符串添加到结构时程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17061358/

相关文章:

c++ - __forceinline 和内联用法

使用 CompareTo 的 VB.NET 排序顺序 - 结果不正确?

c - C中默认的数据结构是什么?

java - 如何解决中缀表示法而不将其转换为任何其他表示法?

java - 将矩阵存储在数组中

c++ - 我需要一个库来加载图像

c++ - 使用节点实现重新填充堆栈

c++ - TinyXML 元素提取为文本

python - 字符串切片参数

javascript - 将脚本放入脚本中