简体   繁体   English

如果我们使用“字符指针”作为C ++中字符数组的索引,则输出是什么?如何在c SHarp中实现此目标?

[英]What is the output, if we use a “character pointer” as an index to a character array in C++ and how to achieve this in c SHarp?

I have a VC++ character array "wchar_t arr[0x30] = { 0x0,0x1,..., 0xC...hexadecimal initialization here ......} ". 我有一个VC ++字符数组“ wchar_t arr [0x30] = {0x0,0x1,...,0xC ...十六进制初始化在这里}} There is one more C++ character pointer wchar_t * xyz . 还有一个C ++字符指针wchar_t * xyz
An operation something like---- wchar_t ch = arr[xyz[2]] is done. 完成了类似wchar_t ch = arr [xyz [2]]的操作。 Can someone kindly explain in detail what is happening in this, because arr[] is a char array and we should pass an integer as an index to any array right? 有人可以详细解释一下这是怎么回事,因为arr []是一个char数组,我们应该将整数作为索引传递给任何数组吗? But here the index passed to the character array "arr[] " is another character pointer xyz[2]. 但是这里传递给字符数组“ arr []”的索引是另一个字符指针xyz [2]。 In the above code suppose a character 'a' is stored at xyz[2] than does it mean we are indexing a C++ character array like this--- arr[xyz[2]] becomes arr['a']. 在上面的代码中,假设字符“ a”存储在xyz [2]上,这并不意味着我们正在像这样索引C ++字符数组-arr [xyz [2]]变为arr ['a']。 Kindly let me know. 请让我知道。 How can I achieve this in c SHarp.. Probably if I get to know that what is happening in C++ code above I can myself achieve it in C SHarp. 我如何在c SHarp中实现这一目标。可能,如果我知道上述C ++代码中正在发生的事情,我自己可以在C SHarp中实现。 Can anyone kindly let me know what is happening here in this C++ code. 谁能让我知道此C ++代码在这里发生了什么。

What happens is that the wchar_t stored at xyz[2] is promoted to an int , then used as an index into the arr array. 发生的情况是将存储在xyz[2]处的wchar_t 提升int ,然后用作arr数组的索引。

It also means that, if xyz[2] contains L'a' , the program will exhibit undefined behavior , since arr only has space for 48 items but L'a' will be promoted to 97 . 这也意味着,如果xyz[2]包含L'a' ,则该程序将表现出不确定的行为 ,因为arr仅可容纳48项目,而L'a'将被提升为97

Concerning the second part of your question, C# only supports pointer arithmetic inside unsafe blocks, so you'll probably want to use arrays instead: 关于问题的第二部分,C# unsafe块内支持指针算术,因此您可能想使用数组代替:

char[] arr = new char[0x30];
char[] xyz = Something();
char ch = arr[xyz[2]];

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

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