Question

I think the standard library could call the sizeof operator on the template type (no ?) in code like that :

#include <fstream>

int main()
{
    std::ofstream file("test.bin", std::ios::binary | std::ios::out);
    char buf = 42;

    file.write(&buf, sizeof(buf));
}

So is there a reason to ask the programmer for the size of the element to write in ostream::write() ?

PS : This is my first question and i'm not english, be indulgent

Was it helpful?

Solution

A char * might be

char const c = 'a';
char const * ptr = &c;        // char const *

as in your example, but it could also be a string literal

std::string x("some string");
char const * ptr = x.c_str(); // also char const *!!

When you have just the pointer available, how do you decide up to what memory address you read? You need a length:

file.write(x.c_str(), x.length());

OTHER TIPS

You can't get size from pointer. ostream::write

ostream& write (const char* s, streamsize n);

here s just points to a location , using sizeof on this won't let you know how many bytes you need to write, instead it will just give you size of pointer.

You cannot find out the size of a pointer to an array without knowing the amount of elements.

Sizeof(ptr) returns either the size of the platform pointer (8 bytes) or the size of the pointed-to structure depending on the operator used.

char * ptr = "abcdef"

printf("%ld", sizeof(ptr));
printf("%ld", sizeof(*ptr));

The first returns 8(platform dependent), the second 1. Even through the 'correct' size is 6.

Therefore in order to know the size of the buffer, you must pass the size as an additional parameter.

For the same reason memset and memcpy require the user to specify the size of the pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top