当试图向结构中添加字符串时,程序中断
Program breaks when trying to add string to structure
我刚开始学习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。
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- 重新运行程序和字符串流?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何使用将字符串拆分为 for 循环中的变量的程序
- win 表单应用程序字符串^ 到 int
- SDL2 程序只写入部分字符串
- 如何保护非托管应用程序中的字符串不受进程转储的影响
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 反转字符串程序中的分段错误
- C++简单的字符串程序
- 即使包含字符串C++程序的编译错误
- 需要帮助弄清楚为什么我的反向字符串c++程序正在崩溃
- 导致运行反向字符串程序时停止工作
- 查找禁止的字符串程序
- 字符串程序中C++错误
- 字符串程序C++运行时错误
- 回文子字符串程序无法运行