C++ using pointers, nothing is passed
Code executes, but nothing gets passed on image_data (line 44 the write_function)
So I have no working array for the function (line 11), why is that so? I thought passing on the reference for image_data should be enough? (I'm used to it, mostly developing JAVA)
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
//Expects bgra image开发者_Go百科 data
//Only makes bgr and bgra with 8 bits per pixel pictures
//Expects big endian ushorts
//makes no checks on the data supplied!
void write_tga(ofstream& output,char image_data[],unsigned short xWidth,unsigned short yWidth,bool transparency) //Line 11 - Line 11 - Line 11 - Line 11
{
char zero = static_cast<char>(0x00);
char two = static_cast<char>(0x02);
//Convert uint to char Array
unsigned char xWidth_arr[2];
unsigned char yWidth_arr[2];
memcpy(xWidth_arr, &xWidth, 2);
memcpy(yWidth_arr, &yWidth, 2);
char header[18] = {zero,zero,two,zero,zero,zero,zero,zero, zero,zero,zero,zero, xWidth_arr[0],xWidth_arr[1],yWidth_arr[0],yWidth_arr[1],static_cast<char>(0x18),zero};
//enabling transparency
if(transparency){
header[16]= static_cast<char>(0x20);
header[17]= static_cast<char>(0x08);
}
char footer[26] = {zero,zero,zero,zero,zero,zero,zero,zero, 'T','R','U','E','V','I','S','I','O','N','-','X','F','I','L','E','.',zero};
output.write((char*)&header,sizeof(header));
output.write((char*)&image_data,sizeof(image_data));
output.write((char*)&footer,sizeof(footer));
output.close();
cout << image_data[0] << endl;
}
int main()
{
ofstream output("data.tga",ios::binary);
output.seekp(0);
char zero = static_cast<char>(0x00);
char image_data[12] = {static_cast<char>(0xff),static_cast<char>(0xff),static_cast<char>(0xff), zero,zero,zero, zero,zero,zero, zero,zero,zero};
write_tga(output,image_data,2,2,false); //Line 44 - Line 44 - Line 44 - Line 44
return 0;
}
What exactly are you trying to do in this code:
output.write((char*)&image_data,sizeof(image_data));
Array name is a pointer. You're writing to output
its content (the memory address), not the actual data it points to. Remove the &
operator to write the content it points to, which is what you wanted, I think. Or use &
on the first member (e.g.: (char*)&image_data[0]
).
sizeof
returns a size of a pointer for image_data
. Use a "size" parameter to convey the size.
And you're abusing static_cast
for no apparent reason.
C++ does not have dynamic arrays. There's an unfortunate syntax choice that char imagedata[]
may be used as a parameter, but it's actually treated as a char * imagedata
. This means that the sizeof operator is returning the size of a pointer, not the size of the array.
精彩评论