c++arrayspointerscastingvoid-pointers

Casting a void pointer to a 2D String array pointer


I'm using a library which requires a function with a void* pointer as a parameter. I have a 2D string array and I want to pass that array through that parameter and extract it inside the function. I successfully passed the array as a pointer but I don't know how to convert that pointer back to my array.

This is my current code:

String str_array[100][10];

int callback(void* data) {

  String* str_array_ptr[100][10] = (String* [100][10])data;

  (*str_array_ptr)[0][0] = "text";

  return 0;

}

void test() {
  callback(&str_array);
}

However, when compiling, I obtain the following error message:

error: ISO C++ forbids casting to an array type 'String* [100][10]' [-fpermissive]

PS: I'm trying to use the SQLite library's sqlite3_exec() function and store the result of a "SELECT SQL query" into a 2D string array.

SQLite C Interface - One-Step Query Execution Interface


Solution

  • You cannot cast a pointer to an array. Instead you access your array through another pointer. That pointer has type String (*)[10]. Like this

    String str_array[100][10];
    
    int callback(void* data) { 
    
        String (*str_array_ptr)[10] = (String (*)[10])data;
    
        str_array_ptr[0][0] = "text"; // Note no '*'
    
        return 0;
    
    }
    
    void test() {
        callback(str_array); // Note no '&'
    }
    

    Both the way you create the pointer, you don't need to use &, and the way you access the pointer, you don't need to use *, are also wrong in your code. See the code above for details.

    The fundamental issue here (and maybe the issue you are misunderstanding) is the difference between String *x[10]; and String (*x)[10];. In the first case x is an array of 10 pointers to String, in the second case x is a pointer to an array of ten String. It's the second option that you want.