0

我正在尝试使用双指针**通过另一个结构'Dict'访问结构'Word'的成员,但在Visual Studio 2010中出现'访问冲突'错误。我也在stackoverflow上检查了链接“访问结构的双指针”,但它也没有解决问题。有人可以帮我识别代码中的错误吗?我在这里内联代码:

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

#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

也许你应该放弃双指针并做出类似的事情:

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


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

主要是:

dic->word = new Word;
dic->word.next = nullptr;

strcpy(dic->word->word,"hi");

然后使用下一个指针使单词成为链表。

编辑:上述解决方案不能使用,因为原始结构应保持不变。

也许尝试类似:

Dict *dic = new Dict;;
dic->size=0;
dic->capacity=MAX_NUMBER_OF_WORDS;
dic->wordArray=new Word *[dic->capacity];

以及插入新词时:

dic->wordArray[dic->size] = new Word;
dic->size++;

并添加容量与大小的检查以避免溢出。

顺便说一句:记得使用 delete 和 new 创建的所有内容。

于 2015-01-16T17:51:09.980 回答
0

查看您的代码,我认为 struct Dict 中的 Word 没有理由应该是双指针。

但我看到了一个很好的理由,为什么 struct Word 中的 char 应该是一个双指针——它是一个“字数组”或 char 的二维矩阵。

所以我提出了这个可行的修改......

#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 回答