I am trying to write and read string to/from binary file, but I can't understand why sizeof(t) returns 4.
//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
char* t = new char[s.length()+1];
strcpy(t, s.c_str());
cout << s.length()+1 << " " << sizeof(t) << endl; // prints 9 4
for(int i = 0; i < sizeof(t); i++)
{
//t[i] += 100;
}
f1.write(t, sizeof(t));
f1.close();
// read from file
ifstream f2("example.bin", ios::binary | ios::in);
while(f2)
{
int8_t x;
f2.read((char*)&x, 1);
//x -= 100;
cout << x; //print Valee
}
cout << endl;
f2.close();
It doesn't matter what size I put in char* array t, code always prints "4" as its size. What must I do to write longer than 4 bytes of data?
sizeof(t)just gives you the size of a pointer, because that's whattis. If you want the size of the memory you allocated fort, why not dos.length()+1instead?char *? string has adata()and thats probably all you needsizeof(t)->strlen(t). But consider the second comment.