5

Converting string to char* is easy in c#

string p = "qwerty";
fixed(char* s = p)

But does anyone know how to convert char[,] into char** in c#?

4
  • 4
    In most languages 2 dimensional arrays aren't stored in a way that is compatible with char**. I'm not sure of C#'s implementation, but I'd suspect the 2D array is just stored as a contiguous block of length x*y, which would be equivalent to a char*. Commented Dec 5, 2015 at 16:57
  • @Bobby Sacamano you are awesome :D I had to use char[,] p = new char[2, 2]; p[0, 0] = '1'; p[0, 1] = '2'; p[1, 0] = '3'; p[1, 1] = '4'; fixed (char* s = p) and it works. Commented Dec 5, 2015 at 17:03
  • @bobby you night want to add it as answer. Else OP could do that. Commented Dec 5, 2015 at 18:44
  • @PatrickHofman That comment was mostly based off something I read in WG21 a while ago. OP should probably answer it, since he has some evidence that this was correct. Commented Dec 5, 2015 at 18:50

1 Answer 1

1

The code below shows how to convert a char[,] array to a pointer. It also demonstrates how chars can be written into the array and retrieved through the pointer. You could also write using the pointer and read using the array. It's all the same, as it references the same data.

            char[,] twoD = new char[2, 2];

            // Store characters in a two-dimensional array
            twoD[0, 0] = 'a';
            twoD[0, 1] = 'b';
            twoD[1, 0] = 'c';
            twoD[1, 1] = 'd';

            // Convert to pointer
            fixed (char* ptr = twoD)
            {
                // Access characters throught the pointer
                char ch0 = ptr[0]; // gets the character 'a'
                char ch1 = ptr[1]; // gets the character 'b'
                char ch2 = ptr[2]; // gets the character 'c'
                char ch3 = ptr[3]; // gets the character 'd'
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.