将 void 指针转换为 2D 字符串数组指针

问题描述 投票:0回答:2

我正在使用一个库,它需要一个带有

void*
指针作为参数的函数。我有一个 2D 字符串数组,我想通过该参数传递该数组并将其提取到函数内。我成功地将数组作为指针传递,但我不知道如何将该指针转换回我的数组。

这是我当前的代码:

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);
}

但是,在编译时,我收到以下错误消息:

错误:ISO C++ 禁止转换为数组类型 'String* [100][10]' [-fpermissive]

PS:我正在尝试使用 SQLite 库的

sqlite3_exec()
函数并将“SELECT SQL 查询”的结果存储到二维字符串数组中。

SQLite C 接口 - 一步查询执行接口

c++ arrays pointers casting void-pointers
2个回答
5
投票

不能将指针强制转换为数组。相反,您可以通过另一个指针访问数组。该指针的类型为

String (*)[10]
。像这样

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 '&'
}

创建指针的方式(不需要使用

&
)和访问指针的方式(不需要使用
*
)在代码中也是错误的。详情请参阅上面的代码。

这里的根本问题(也许是您误解的问题)是

String *x[10];
String (*x)[10];
之间的区别。在第一种情况下
x
是一个由 10 个指向
String
的指针组成的数组,在第二种情况下
x
是一个指向由 10 个
String
组成的数组的指针。这是您想要的第二个选项。


2
投票

String* str_array_ptr[100][10];
没有声明指向
String
对象的 2D 数组的指针;相反,它声明了一个指向
String
对象的指针的 2D 数组。

声明指向二维数组的指针的语法很棘手;在您的情况下,它如下(将

str_array_ptr
声明为指向 100 x 10
String
对象数组的指针):

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

转换为这样的指针(可以说)更加棘手;使用 C++

static_cast
(当源操作数是
void*
时可以),您将得到以下代码:

#include <iostream>
#include <string>
using String = std::string;

String str_array[100][10];

int callback(void* data) {

    String (*str_array_ptr)[100][10] = static_cast<String (*)[100][10]>(data);
    (*str_array_ptr)[0][0] = "text";
    return 0;
}

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

One could 认为,如果您确实希望使用这样一个指向 2D 数组的指针(C++ 中可能有更好的设计解决方案,例如 john 发布的答案),那么您 could 定义一个类型对于带有

typedef
using...
语句的指针(例如
using StrArrPtrType = decltype(&str_array);
);然而,C++ 和 C 编程社区通常对将指针隐藏在
typedef
using
别名后面表示不满(严重且正确)。

© www.soinside.com 2019 - 2024. All rights reserved.