Search code examples
c++carraysargument-passingfunction-declaration

How to pass a pointer as an array argument?


I have a third-party library, which has a function delared as follows:

void foo(const void* input, char output[1024]);

If I write something like this:

char* input = "Hello";
char  output[1024];
foo(input, output); // OK

But I don't want to declare such a big array on stack (that would be very dangerous in OS kernel environment). So I have to do something like this:

char* input      = "Hello";
char* output_buf = new char[1024];
foo(input, output_buf); // Compiler Error C2664

I cannot change the implementation of foo. How should I do?

=================

The problem has been resolved. My real code is like this:

char* input      = "Hello";
void* output_buf = new char[1024];
foo(input, output_buf); // Compiler Error C2664

conversion from void* to char* is not implicitly accepted by the standard. So the following code works:

char* input      = "Hello";
void* output_buf = new char[1024];
foo(input, (char*)output_buf); // OK

Solution

  • The problem is not with output. In reality your function does not take an array as you cannot pass arrays to functions. It receives a pointer to char. This would work as well:

    void foo(char f[1024])
    {
        // blah
    }
    
    int main() {
        char c1[1];
        foo(c1);  // works!
    
        char *c2 = new char[27];
        foo(c2);  // works!
    
        delete [] c2; 
    }
    

    That code will compile, and it does so because the function receives a pointer, that is all. So, the problem is with your first argument, input. It's type must be wrong. Look at your error message more closely and/or show us the declaration of input.