Hello,
Here is a function similar to the one I've defined:
void Function( BYTE *data );
What I would like to do is something like this:
Function( new BYTE { 0x00, 0x00 } );
Hello,
Here is a function similar to the one I've defined:
void Function( BYTE *data );
What I would like to do is something like this:
Function( new BYTE { 0x00, 0x00 } );
You cannot use the array initialiser syntax with dynamically allocated arrays using new
. You could do something like this:
BYTE *ary=new BYTE[2];
ary[0] = 0;
ary[1] = 0;
Function(ary);
delete [] ary;
But why are you using dynamically allocated memory here? Is the array held onto outside of the scope of the current function? If not, you can use an array allocated on the stack:
BYTE ary[2] = {0};
Function(ary);
In C++, a preferred method is to use the STL class std::vector
which acts like a dynamically allocated (but type safe) array:
std::vector<BYTE> ary(2);
Function(&ary[0]);
Well, if BYTE is a Class, you could have a constructor
BYTE::BYTE(char c1,char c2){
//something here.
}
and then call
Function( new BYTE(0X00,0X00))
However, this is leak-prone. You should delete the argument before exiting Function. And that's not always possible (e.g if you don't have Function's source)
BYTE foo[] = { 0x00, 0x00 };
Function( foo );
C++0x will introduce initializer list syntax that will allow something closer to what you wanted above.
Auxiliary function;
BYTE* makeNaryByteArray( int n, BYTE exemplar = 0 ) {
BYTE* r = new BYTE[ n ];
for( int i = 0 ; i < n ; ++i )
n[i] = exemplar;
return r;
}
//call them:
BYTE* myByteArray;
Function( myByteArray = makeNaryByteArray(2) );
// done with array:
delete[] myByteArray;
Just remember, arrays created with new[]
are deleted with delete[]
;
#include <windows.h>
#include <iostream>
using namespace std;
void foo(BYTE *d) {
cout << (int)d[ 0 ] << " " << (int)d[ 1 ] << endl;
}
int main(void)
{
foo(new BYTE[ 2 ]());
return 0;
}
The above works if all you ever wanted was to initialize the BYTE
array to all zeroes. (I am assuming this is the Windows BYTE
type.) However this is leak-prone as mentioned and is best avoided.
Or you could use the ellipsis to mimic construction of your array:
take a look at this: http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/
And if you really want to fiddle before the 0x arrives, take a look at this code.
gcc has an extension called "Compound literals", which allows you to write:
Function((BYTE[]){1, 2, 3, 4});
Note that it is allocated on the stack, so it might not be suitable for your purposes.