简体   繁体   中英

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 ......} ". There is one more C++ character pointer wchar_t * xyz .
An operation something like---- wchar_t ch = arr[xyz[2]] is done. 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? But here the index passed to the character array "arr[] " is another character pointer 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']. 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. Can anyone kindly let me know what is happening here in this C++ code.

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.

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 .

Concerning the second part of your question, C# only supports pointer arithmetic inside unsafe blocks, so you'll probably want to use arrays instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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