For a problem, I have to use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order. However, I cannot even get the read function to work properly. This is what it wrote:
void readNames(std::string* a[])
{
std::ifstream fin;
fin.open("names.txt");
for (int i = 0; i < 7; ++i)
{
fin >> *(a[i]);
std::cout << *a[i];
}
}
This is how I called it in main:
std::string* names;
names = new std::string[7];
readNames(&names);
However, when I run this I get the error:
Exception thrown: read access violation. this was 0xCCCCCCCC.
And this function is displayed(not sure if this helps):
void _Check_offset(const size_type _Off) const { // checks whether _Off is in the bounds of [0, size()]
if (_Mysize < _Off) {
_Xran();
}
}
If anyone can help me with this I would relly appreciate it, thank you!
(*a)[i]in all contexts inreadNameswill do what you want, but passing name by address still has a pretty bad code smell. I see no reason to pass that pointer by address in the first place unless the API itself is fixed (and it certainly doesn't look like it), and frankly I'd change both the caller and function, or better still, use a vector of strings instead.0xCCCCCCCCmeans uninitialized stack memory: https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representationsvoid readNames(std::string* a[])would be better written (provided there are always 7 elements) asvoid readNames(std::array<std::string,7> & arr)or maybestd::array<std::string,7> readNames()void readNames(std::string* arr, int numElements)instead ofvoid readNames(std::string* a[])