Hello, wondering if someone can help me quickly..

Basically, I have created a array to store all the data in a text file. The pointer of the array is sent to a function, which then populates it. Here is the code:

void Data(char* theData)
    ifstream txtFile(inputFile.c_str());
        cerr << "Cannot open text file";

    char getData[100000];
    txtFile.read(getData, sizeof getData);

    theData = getData;

int main(int argc, char *argv[]) {

    char* data;

    cout << data[0];


I get a segmentation fault, and I think it's to do with how I'm copying getData into theData.

Could anyone help ?


5 Years
Discussion Span
Last Post by Ancient Dragon

Two problems with that code
1. theData in Data() is just a local variable, so line 12 us useless, does nothing.
2. arrays declared inside function can not be returned from the function, attempting to do so will cause sig faults, as you have found out.

To correct the problem, move line 9 to line 17 so that it is declared inside main() instead of Data, then pass it as the parameter to Data(). You will also have to pass the size of the array as another argument to Data() because sizeof does not return the size of an array when used with a pointer.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.