动态内存分配,正在读取中的文件
Dynamic Memory Allocation with reading file in
我正在尝试为这个项目使用动态内存。我犯了一个seg错误,但我不知道我做错了什么。有人能指出我的错误在哪里吗?文件似乎读取正确。。。但我认为错误是一个无赖的指针。。帮助
我只是想从一个文件中读"心二2"到"王牌11",所有的单词都用空格隔开。我的程序在使用动态内存之前就工作了。。
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
#include <string>
using namespace std;
//global constant(s)
const int maxCards = 52;
//Structs
struct card
{
char *suit;
char *rank;
int cvalue;
char location;
};
void readDeck(card* deckPtr);
void cardsInit(char *finNameP,card *deckPtr);
//program
int main()
{
card *deckPtr = new card[52];
char *finNameP = new char[13];
strcopy(finNameP,"cardFile.txt");
cardsInit(finNameP,deckPtr); // function i wrote that works
readDeck(deckPtr); //simply reads the deck from &deckPtr[0] -> &deck[51]
delete [] finNameP;
}
void cardsInit(char *finNameP, card *deckPtr)
{
//set up card file to be read in
ifstream fin;
cout << "Please enter file name...(cardFile.txt)" << endl;;
cin >> *finNameP;
fin.open(finNameP);
//create pointer and set initial value
card *deckHome = deckPtr;
for(int i=0;i<52;i++)
{
(*deckPtr).suit = new char[9];
(*deckPtr).rank = new char[9];
deckPtr++;
}
deckPtr = deckHome;
//check if cardFile.txt opens correctly
if(!fin.good())
{
cout << "Error with card file" << endl;
}
else
{
while(fin.good())
{
for(deckPtr = &deckPtr[0]; deckPtr < &deckPtr[maxCards];deckPtr++)
{
fin >> (*deckPtr).suit;
fin >> (*deckPtr).rank;
fin >> (*deckPtr).cvalue;
}
}
}
fin.close();
delete []finNameP;
delete [] (*deckPtr).suit;
delete [] (*deckPtr).rank;
}
这是一种非常古老的编程方式。不要使用new
,而是使用std::string
或std::vector<char>
。它们也使用动态内存,但它们会使您更难意外地导致内存分配错误。
第一个问题出现在这里:
cin >> *finNameP;
由于finNameP
具有类型char *
,则*finNameP
具有类型char
。所以这个指令只读取一个字符。然后继续执行fin.open(finNameP);
,这会导致未定义的行为,因为finNameP
中没有字符串。
最简单的修复方法是将finNameP
设为std::string
。请注意,执行cin >> finNameP
(不更改类型)将进行编译,但这不是一个好主意,因为没有缓冲区溢出保护。您可以编写cin >> setw(12) >> finNameP;
,但这仍然比使用字符串差得多。
deckPtr < &deckPtr[maxCards]
始终为true,for循环将永远运行。
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中