简体   繁体   English

C ++ 2维静态数组与2维动态指针兼容

[英]c++ 2 dimensional static array compatible with 2 dimensional dynamic pointer

Is there a way to declare 2 dimensional static array which is compatible with the dynamic pointer (TYPE**) ? 有没有办法声明与动态指针(TYPE **)兼容的二维静态数组?

char strs1[2][256] = { "String 1", "String 2" }; // Static

What I want is to assign it to 我要分配给

char **strs2 = strs1;

Well, I can do something like that: 好吧,我可以做这样的事情:

std::array<std::array<char, 256>, 2> arr = {"String 1", "String 2"};
char *temp[2] = { (char*)&arr[0], (char*) &arr[1] };
char **strs = (char**)temp;

cout << strs[0] << endl;
cout << strs[1] << endl;

// Output
String 1
String 2

But is there a better and simpler way to achieve the same result ? 但是,有没有更好,更简单的方法来达到相同的结果呢?

char** can never be a way to reference a an array of arrays (there are no two-dimensional arrays in C/C++) because it doesn't have the information on the inner array size. char **永远不是引用数组数组的方法(C / C ++中没有二维数组),因为它没有有关内部数组大小的信息。 In particular, there is no way compiler can generate a proper access code in following snippet: 特别是,编译器无法在以下片段中生成适当的访问代码:

char** arr = initialize_by_hack();
arr[2][4] = '42';

Here, to calculate second offset (4) compiler needs to know the size of element array - but is is nowhere in the code and not available. 在这里,要计算第二个偏移量(4),编译器需要知道元素数组的大小-但是在代码中没有位置并且不可用。

No, you cannot change the fact that a two-dimensional array is incompatible with a T** . 不,您不能更改二维数组与T**不兼容的事实。

You can only perform hacky workarounds like the one you posit in your question, or remedy the mistake or design flaw that initially led you to the requirement. 您只能执行像您在问题中提出的那样的棘手解决方法,或者纠正最初导致您提出要求的错误或设计缺陷。

Since you're writing C++: why not use proper, modern, type-safe technologies rather than native arrays and a mess of pointers? 既然您正在编写C ++:为什么不使用适当的,现代的,类型安全的技术,而不要使用本机数组和一堆指针? A simple Matrix<T,W,H> class template that wraps a statically allocated T[W*H] but exposes two-dimensional indexing would be nice. 一个简单的Matrix<T,W,H>类模板,它包装了一个静态分配的T[W*H]但是却公开了二维索引。 Then just pass it around by reference (or, if you really must, by pointer). 然后只需按引用传递它(或者,如果确实需要,则按指针传递)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM