Reputation: 1005
I have a unsigned c++ char buffer
unsigned char* pBuffer = new unsigned char [1024];
I want to save the pBuffer
pointer in the first few bytes of the newly allocated buffer by using an assignement rather than memcpy- ie
*(unsigned char*) &pBuffer[0] = pBuffer;
I am not able to get the sytax right. Appreciate help with the correct syntax for doing this.
Visual Studio 2010
Upvotes: 0
Views: 671
Reputation: 66922
I don't know why you would want to do this, but I can think of a few oddball reasons, so:
reinterpret_cast<unsigned char**>(pBuffer)[0] = pBuffer;
You want the compiler to reinterpret the pointer as a unsigned char**
, and store the value of pBuffer
in the 0-index slot.
You said you're indexing a "linked list" with multiple pBuffers. In that case, you should not use reinterpret_cast. Instead:
struct node {
node* prev;
std::unique_ptr<node> next;
unsigned char buffer[1024];
node(node* prev_) : prev(prev_) {}
};
std::unique_ptr<node> list(new node(nullptr)); //tada
Upvotes: 3
Reputation: 12930
Not sure why you are doing this, but this works with my g++
compiler:
*(unsigned char**)pBuffer=pBuffer;
Upvotes: 0
Reputation: 409176
How about:
*((unsigned char**) pBuffer) = pBuffer;
It casts the pBuffer
pointer to a pointer to a pointer to a char, and then dereferences that to make it a pointer to a char that is then assigned the pBuffer
pointer.
It might be easier to understand if we write it like this:
unsigned char **ppBuffer = &pBuffer;
*ppBuffer = pbuffer;
Upvotes: 1