问题
I am reading a binary file with fstream and storing the information in an array of characters:
int dataLength = 32;
int counter = 0;
char data[dataLength];
char PMTone[dataLength/4];
std::fstream *fs = new std::fstream(inputFileName,std::ios::in|std::ios::binary);
fs->read((char *)&data, dataLength);
//of the 32 characters in data[], I need first, 5th etc elements:
//fill first pmt info
for(int i=0; i<(dataLength/4); i++){
PMTone[i]=data[counter];
counter+=4;
}
Now I'm setting PMTone[7] to be a as a test:
PMTone[7] = "a";
I get the error:
mdfTree.cpp:92:21: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
I don't understand why the elements in PMTone[] are pointers to chars, when PMTone[] was defined as an array of chars.
When I do treat PMTone[] as an array of pointers to chars:
(*PMTone)[7] = "a";
I get another error that I don't understand:
mdfTree.cpp:91:18: error: invalid types ‘char[int]’ for array subscript
This seems to imply that the compiler doesn't consider PMTone[] to be an array at all, but simply a pointer to char.
Can anyone shed light on what is happening here? Why has PMTone[] become an array of pointers to chars?
回答1:
The literal "a"
is not a character.
You need:
PMTone[7] = 'a';
回答2:
"a"
is not a character it is an array of characters, 'a' followed by a null terminator.
You would need
PMTone[7] = 'a';
with single quote. Incidentally I am surprised that it compiles earlier because dataLength wasn't declared as const.
PMTone
itself is of type char[8]
which is an array of characters. However it decays to a pointer and (*PMTone)
is the first element, of type char
回答3:
An array is a way of storing values by having the address of the first element and accessing other elements by index. An array is basically a pointer to the first element.
When you create an array of chars
char arr[n];
program actually creates room for n characters in the memory.
When accessing arr[0]
let's say like this:
arr[2] = 'a';
program is actually doing this:
*(arr + 2) = 'a';
meaning you are accessing a character which is stored 2 Bytes further from the memory location of the first element in the array (hence, the arr + 2
), with the first element being arr[0]
.
The address of the first element is &(arr[0])
or, arr
. Both are the same values.
The bug is where you tried saving a string "a"
into a char
.
The problem is you tried fixing it by dereferencing a dereferenced pointer:
(*PMTone)[7] = "a"; // is the same as
(PMTone[0])[7] = "a"; // when it should be
PMTone[7] = 'a';
来源:https://stackoverflow.com/questions/13007862/reading-binary-file-with-fstream