My task involves finding the longest common substring in two txt files using suffix arrays. I have done the following:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <fstream>
int main() {
char* charArrayA = charArrayFromTxtFile("~/txt_file1.txt");
char* charArrayB = charArrayFromTxtFile("~/txt_file2.txt");
int lengthA = strlen(charArrayA);
int lengthB = strlen(charArrayB);
char* suffixArrayA[lengthA];
char* suffixArrayB[lengthB];
for(int i = 0; i < lengthA; i++) { suffixArrayA[i] = &charArrayA[i]; }
for(int i = 0; i < lengthB; i++) { suffixArrayB[i] = &charArrayB[i]; }
charArrayA[lengthA] = 0;
charArrayB[lengthB] = 0;
...
return 0;
}
However, when I compiled this portion of code, I get the following error flag at the line containing the SECOND for-loop:
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef1446e0)
For reference, the function I use to create charArrayA and charArrayB is:
char* charArrayFromTxtFile(std::string fileName) {
std::ifstream filename; // Variable for file
int length; // Number of characters
filename.open(fileName);
filename.seekg(0, std::ios::end); // Goes to the end of the file
length = filename.tellg(); // Location of the end (index, length of file)
filename.seekg(0, std::ios::beg); // Go back to the beginning
char* charArray = new char[length]; // Allocate a char array of "length" file
filename.read(charArray, length); // Write characters from txt file into the char array
filename.close();
return charArray;
}
Anybody know why it would be the case that the first txt file doesn't give me any trouble, but the second one does? I'll appreciate any guidance. Thanks so much guys!
P.S. This is my first stackoverflow question, so hopefully I was clear enough. I'll appreciate any feedback in question form as well! :D