gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:16 24 4
gpt4 key购买 nike

<分区>

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

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