Kiarash
Kiarash

Reputation: 7998

writing part of an array to file in C++

I want to write k elements starting from k*i to a file. so in a for loop I write as below:

    testOut.write((char*) h_test[k*i] ,k*sizeof(float));

I get this error "invalid cast from type ‘float’ to type ‘char*’ "

How should I correct this?

Upvotes: 0

Views: 334

Answers (2)

Diego Sevilla
Diego Sevilla

Reputation: 29011

If you want to write them in binary, you can do as follows:

testOut.write( reinterpret_cast<const char*>(h_test + k*i), k*sizeof(float));

h_test + k*i is the address of a float pointer, that you reinterpret to a const char* so that write can take it. Note that adding to a pointer increments the pointer taking into account the pointed element size, and you convert the pointer after.

Finally, write accepts a const char*, not char*.

Upvotes: 3

icktoofay
icktoofay

Reputation: 129001

I assume write takes a char * and a size. Try this:

testOut.write((char*)&h_test[k*i], k*sizeof(float));

h_test is probably an array of floats. You tried to dereference it like this:

h_test[k*i]

That's a float, not a float *. To make it a pointer, you use the & operator.

Upvotes: 1

Related Questions