C++ 修复:访问冲突读取位置(指向字符串数组的指针)
固定的: 第一个帖子/问题 <>这是C++,我正在尝试打印一个单词数组。< /P>C++ 修复:访问冲突读取位置(指向字符串数组的指针),c++,arrays,pointers,struct,access-violation,C++,Arrays,Pointers,Struct,Access Violation,固定的: 第一个帖子/问题 这是C++,我正在尝试打印一个单词数组。< /P> #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <cstring> #include <cctype> #include <ctime> using namespace std; //structs struct
#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
}
5是动态分配数组的大小,其余是字符串,正如您可以看到的,有6个字符串,因此我在for循环中测试了文件是否仍在将字符串传输到数组。文件到数组的这一部分导致了问题:
word = new string [size];
您认为您正在将myInput
对象的指针设置为指向字符串数组,但实际上并非如此。将指针传递到此处的函数时:
File_to_Array(myInput.word, myInput.size)
^^^^^^^^^^^^
您实际上是在传递指针的副本。因此,在文件\u to_数组
中,此副本被重新指向新创建的字符串数组,但myInput
中的实际指针没有更改。您应该传递对指针的引用:
void File_to_Array(string*& word, int &size)
\___________/
^--reference to a pointer
我还建议您使用
向量[string]
。最后,你的bool是回文[]代码>成员和它的初始化看起来很奇怪,但很难进一步评论,因为它们从未在代码中使用过。Input::is_palindrome
应该是一个数组,但你用false
初始化它。哦,所以我正在创建指针的副本。。。好吧,我现在明白了。因此,我必须将指向字符串数组的指针的引用传递到函数中。非常感谢,我现在就试用一下,并报告成功与否。希望是前者。我们(我的班级)还没有学会向量,这是hw assn的一部分,它要求使用特定的东西,其中之一是数组、指针、字符串等诸如此类的东西,而不是向量。非常感谢您的即时帮助。我对这个论坛有点陌生,但到目前为止第一印象很好。我回来告诉你这是有效的,我把bool改成了bool*
void File_to_Array(string*& word, int &size)
\___________/
^--reference to a pointer