动态分配内存到struct array c ++

时间:2014-09-24 18:40:10

标签: c++

让我首先说我知道这是一种时髦的编程方式,但我的老师要求我们这样做。

也: 我可以为这个项目使用std :: string,classes,constructors。 我需要使用这种古老的c风格字符串方法,并在结构外部进行动态内存分配。我知道这不是解决这个问题的最佳方法,但是我不能这样做。 :(

我坚持结构,我不知道什么是错的..

我有一个结构

#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;
};

//Function List
void readPlayers(player *peoplePointer);
void shuffleCards(card *unshuffled, card* shuffled);

//program
int main()
{
    //create pointer and set initial value
    card * deckPointer = new card[52];
    card *deckHome = &deckPointer[0];
    for(int i=0;i<maxCards;i++)
    {
        (*deckPointer).suit=new char[8];
        (*deckPointer).rank = new char[7];
        deckPointer++;
    }
    deckPointer = deckHome;
    cardInit(deckPointer);
    readDeck(deckPointer);

    //sets default values for the card arrays
    for(int i=0;i<52;i++)
    {
        strcopy((*deckPointer).suit,"suit");
        strcopy((*deckPointer).rank,"rank");
        (*deckPointer).cvalue = 0;
        deckPointer++;
    }
    deckPointer = deckHome;
    return 0;
}

//Functions
void cardInit(card *deckPointer)
{
    card * deckHome = NULL;
    deckHome = &deckPointer[0];
    //set up card file to be read in
    ifstream fin;
    char *finName = new char[13];

    //get file name from user
    cout << "Enter file name...(cardFile.txt)" << endl;;
    cin >> *finName;

    //open the file
    fin.open(finName);

    //check if cardFile.txt opens correctly
    if(!fin.good())
    {
        cout << "Error with card file" << endl;
    }
    else
    {
        deckPointer = deckHome;
        while(fin.good())
        {
            for(int i=0;i<50;i++)
            {
                fin >> (*deckPointer).suit;
                fin >> (*deckPointer).rank;
                fin >> (*deckPointer).cvalue;
                deckPointer++;
            }
        }
    }
    delete [] finName;
}

    //Its a pretty simple program..and my dynamic memory works for 
    //the file name, but I cant figure out why it doesnt work for structs?

1 个答案:

答案 0 :(得分:0)

要使您的代码正常工作,您需要一个类型名片。

为此,您需要设置以下内容:

struct cardstruct { 
    char *suit; 
    char *rank; 
    int cvalue; 
};

typedef struct cardstruct card;

否则,当你声明指针时,你需要使用&#34; struct&#34; keword第一。 E.G:

struct card *deckPtr = new struct card[52];