C++ 12.2.0 throws the error
error: cannot convert ‘unsigned char (*)[91]’ to ‘unsigned char**’
on the following c++11 code snippet:
unsigned char buffer[91];
// int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp);
ptrdiff_t length = i2d_PUBKEY(m_pkey, &buffer);
- Defining
unsigned char *bufferfixes the error, but leaves the array length unspecified. - I had assumed
unsigned char buffer[91]decays intounsigned char *buffer.
Explicitely casting like i2d_PUBKEY(m_pkey, (unsigned char **)&buffer) makes the error go away, but the code segfaults then. I suppose there is something fundamental I don’t understand with respect to C++ arrays.
Can someone tell me how to write the code above so it works as intended?
>Solution :
The first thing to note is that neither of two pointers in the signature is const. This alone should warn you because the function could modify data at two different locations, but you’re passing only one (unless you expect buffer itself to change, which I guess you don’t). The documentation reads:
If
ppis notNULL, it writes the encoded data to the buffer at*pp, and increments it to point after the data just written.
Let’s introduce the second variable to be modified:
unsigned char* ptr = &buffer[0];
Now we can pass this variable to i2d_PUBKEY():
i2d_PUBKEY(/* ... */, &ptr);
This call will write data into *ptr, i.e. into buffer. ptr itself will be modified, and that’s why ptr can’t be passed by value and a second pointer is needed – or a reference if i2d_PUBKEY() were a C++ function.