在c ++中动态分配结构数组。为什么数组会被覆盖?

时间:2016-10-10 13:15:32

标签: c++ arrays memory-management dynamic struct

因此,对于学校的作业,我必须动态分配struct Pieces数组,然后使用.txt文件中的代码填充数组。它似乎很好,但每当我在填充数组后检查,它只会说明最后一个元素。如果我尝试检查任何特定元素或者如果我尝试递增,它会崩溃。我已经倾注了这些代码,我无法弄清楚出了什么问题......请帮忙

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

struct Pieces
{
    char* word;
    int jump;
};

void reset(char*, int);
int strLen(char*);
void createArr(char*, char*);

int main()
{
    char* temp;
    int numWords;
    int numKeys;
    int count = 0;
    Pieces* cipher;
    Pieces* resett;
    ifstream input;

    temp = new char[20];
    input.open("Project4Data.txt");
    input >> numWords;
    input >> numKeys;
    cipher = new Pieces[numWords];
    resett = cipher;

    while(input >> temp)
    {
        createArr(cipher->word, temp);
        cipher->word = temp;
        //cout << cipher->word << " ";
        input >> cipher->jump;
        //cout << cipher->jump << endl;
        count++;
        if(count == numWords)
            break;
        cipher++;
        reset(temp, 20);
    }
        input.close();
        cipher = resett;
        cout << *(cipher)->word ;
        delete[] resett;
        delete[] cipher;
        return 0;
}

int strLen(char* word)
{
    int s = 0;
    //cout << word;
    for(int x = 0; *(word + x) != '\0'; x++)
        s++;
    return s;
}

void reset(char* arr, int size)
{
    for(int x = 0; x  < size; x++)
        *(arr + x) = '\0';
}

void createArr(char* a, char* b)
{
    //cout << b << b;
    a = new char[strLen(b)];
}

下面是我们应该使用的文本文件:

23 11

Java 2 linux 3恐惧0池2做0红1锁。 1我0随机2台电脑,0不0 0开2车! 2 C,0缺少0 0狗1绿2 C ++ 0瓶2错2,它们。 0

0 个答案:

没有答案