mercredi 24 mars 2021

why reading a string from a file with the read function works both with the use of & and without using it?

I wrote the following program to see how read function works

    ifstream inputFile;    
    char string[6];
    int integerVariable;
    
    inputFile.open("FILE_TEST.bin", ios :: binary);
    inputFile.read((char *) string, sizeof(char) * 6);
    //inputFile.read((char *) &string, sizeof(char) * 6);
    inputFile.read((char *) &integerVariable, sizeof(int));
    cout << "STRING: " << string << "VAR: " << integerVariable << endl;

In the case of a character string, the function works both using & and without using it. To create the file I also tried to use the write function and it has the same behavior.

    ofstream outputFile;
    char string[] = "TEST\n";
    int integerVariable = 10;
    
    outputFile.open("FILE_TEST.bin", ios :: binary);
    outputFile.write((char *) string, sizeof(char) * 6);
    //outputFile.write((char *) &string, sizeof(char) * 6);
    outputFile.write((char *) &integerVariable, sizeof(int));

I expected that since string is a pointer, then it should not be necessary to use & and putting it should cause an error.

Aucun commentaire:

Enregistrer un commentaire