修正:访问冲突读取位置(指针到字符串数组)

FIXED: Access Violation Reading Location (pointer to string array)

本文关键字:字符串 数组 指针 访问冲突 读取 位置 修正      更新时间:2023-10-16

修正:http://pastebin.com/71QxqGk5

第一篇文章/问题。

这是c++,我想打印一个单词数组

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cctype>
#include <ctime>
using namespace std;
//structs
struct Input
{
    int size;
    string* word;
    bool is_palindrome[];
};
//prototypes
bool openInputFile(ifstream &ifs);
void File_to_Array(string* word, int &size);
void PrintArray(string* word, int size);
//main
int main()
{
    Input myInput = { 0, nullptr, false };
    File_to_Array(myInput.word, myInput.size);//copy arr and get size
    cout << myInput.word; //this outputs 00000000
    cout << *myInput.word; //this breaks and throws exception as commented below
    //Exception thrown at 0x0098BB6B in Project1.exe: 0xC0000005: Access violation reading location 0x00000014.
    PrintArray(myInput.word, myInput.size);//print array of strings
    system("PAUSE");
    return 0;
}
//functions
bool openInputFile(ifstream &ifs)
{
    string filename;
    cout << "Enter the input filename: " << endl;
    getline(cin, filename);
    ifs.open(filename.c_str());
    return ifs.is_open();
}
void File_to_Array(string* word, int &size)//copies file to dyn arr and assigns size from first elem
{
    ifstream myFile;
    while (!openInputFile(myFile))
        cout << "Could not open file" << endl;
    string tempstr = "";
    getline(myFile, tempstr);//first line is size of dyn arr
    size = stoi(tempstr);//now we have max size of dyn arr of strings
    word = new string [size];//now we have the array of strings, *word[index] = string1
    int i;
    for (i = 0; getline(myFile, word[i]) && i < size; ++i);//for each line
    //copy line of string from file to string arr within "bool" test, second param of for loop  //copying done
    size = i;
    myFile.close();//done with file, no need, close it
}
void PrintArray(string* word, int size)
{
    //for (int i = 0; i < size; ++i)
    //cout used to be here, but now its in main, for debugging
}

所以我想知道如果我的问题是传递一个结构体的成员,如果我应该把整个结构体类型"myInput"传递到函数中,并使用->操作符访问myInput的成员。

下面的

是一个文本文件的例子

5
month
Runner
NEON
digit
ferret
nothing

5将是动态分配数组的大小,其余的是字符串,你可以看到有6个字符串,所以我在for循环中测试文件是否仍在将字符串传输到数组。

这部分File_to_Array引起了问题:

word = new string [size];

你认为你正在设置myInput对象的指针指向字符串数组,但你没有。当你将指针传递给这里的函数时:

File_to_Array(myInput.word, myInput.size)
              ^^^^^^^^^^^^

实际上传递的是指针的副本。所以在File_to_Array内部,这个拷贝被重新指向新创建的字符串数组,但myInput内部的实际指针没有改变。你应该传递一个对指针的引用:

void File_to_Array(string*& word, int &size)
                   ___________/
                         ^--reference to a pointer

我还建议您使用vector[string]代替。最后,您的bool is_palindrome[];成员和它的初始化看起来非常奇怪,但很难进一步注释,因为它们从未在代码中使用过。