0

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.

Eduard
  • 61
  • 4
  • 2
    Tightly related: [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – user4581301 Mar 24 '21 at 18:55
  • 3
    With any array, say `char array[100];`, `array` and `&array` are the same address but have DIFFERENT TYPES. `array` is type `char *` (pointer to char). `&array` is type `char(*)[100]` (pointer to array of `char[100]` ) Pointer arithmetic works completely different on the two types. – David C. Rankin Mar 24 '21 at 18:58
  • I understand, thank you very much. Apparently there was already a question in which everything was explained about it – Eduard Mar 24 '21 at 19:03

0 Answers0