我想爲這個項目使用動態內存。我遇到了seg錯誤,但我無法弄清楚我做錯了什麼。任何人都可以指出我的錯誤在哪裏?該文件似乎正確閱讀...但我假設錯誤是一個流氓指針..幫助!動態內存分配與讀取文件在
我只是想從一個文件中讀取「heart two 2」到「spade ace 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;
}
'strcopy'不是什麼東西。確保你複製粘貼你的代碼而不是重新輸入 – 2014-09-24 05:38:59
它是我寫的一個函數。感謝您的毫無價值的回覆 – matt 2014-09-24 05:41:03
你不會看400行代碼..:/ – matt 2014-09-24 05:47:11