0

ダブルポインター**を使用して別の構造体 'Dict' を介して構造体 'Word' のメンバーにアクセスしようとしていますが、Visual Studio 2010 で 'アクセス違反' エラーが発生しました。問題も解決しません。誰かがコードのエラーを特定するのを手伝ってくれませんか? ここにコードをインライン化しています:

============================================

#include <iostream>
#include <stdlib.h>
#include <time.h>
//#include "dict.h"
using namespace std;

enum WordType{All, Animal, Fruit, Name};

struct Word{
    WordType type;
    char word[20];
};

struct Dict{
    int size;
    int capacity;
    Word **wordArray;
};

int main() {

    Dict *dic = new Dict;;
    dic->size=0;
    dic->capacity=0;

    strcpy((dic->wordArray[0])->word,"hi");

    cout<< (dic->wordArray[0])->word;
    system("pause");
    return 0;
}

================================================== ======

4

2 に答える 2

0

あなたのコードを見ると、構造体 Dict の Word が二重ポインタでなければならない理由がわかりません。

しかし、構造体 Word 内の char が二重ポインタでなければならない理由は非常によくわかります。これは、「単語配列」または char の 2D 行列です。

だから私はうまくいくこの修正を提案します...

#include <iostream>
    #include <vector>
    #include <complex>

    #include <iostream>
    #include <stdlib.h>
    #include <time.h>
    //#include "dict.h"
    using namespace std;

    enum WordType{ All, Animal, Fruit, Name };

    struct Word{
        WordType type;
        char** word;
    };

    struct Dict{
        int size;
        int capacity;
        Word wordArray;
    };

    int main() {

        Dict *dic = new Dict;
        dic->size = 0;
        dic->capacity = 0;
        dic->wordArray.word = new char*[4]; // make an array of pointer to char size 4
        for (int i = 0; i < 10; i++) {
            dic->wordArray.word[i] = new char[5]; // for each place of above array, make an array of char size 5
        }

        strcpy_s(dic->wordArray.word[0], strlen("hi") + 1, "hi");
        strcpy_s(dic->wordArray.word[1], strlen("John") + 1, "John");
        strcpy_s(dic->wordArray.word[2], strlen("and") + 1, "and");
        strcpy_s(dic->wordArray.word[3], strlen("Mary") + 1, "Mary");

        cout << dic->wordArray.word[0] << endl;
        cout << dic->wordArray.word[1] << endl;
        cout << dic->wordArray.word[2] << endl;
        cout << dic->wordArray.word[3] << endl;

        system("pause");
        return 0;
    }
于 2015-01-16T18:36:31.010 に答える