当试图向结构中添加字符串时,程序中断

Program breaks when trying to add string to structure

本文关键字:字符串 程序 中断 添加 结构      更新时间:2023-10-16

我刚开始学习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, name, price, year,…)的数据后,程序在这一行中断

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));以确保调用构造函数

temp->name永远不会被构造,所以你不能在赋值操作符的左侧使用它。如果您认为您确实构造了它,请指出您认为构造它的代码行。我打赌你不能。(您为它分配了内存,但您从未在该内存中构造字符串!)

使用new()而不是malloc()来构造你的类。在这种情况下,std::string的构造函数永远不会被调用!

如果你是c++的初学者,我建议你现在总是使用new/delete,而不是malloc/free。