1

I've used C# for several years but have never worked with Pointers in C#. I'm playing around with the String API and I'm lost on why a char* is actually an array and not a single char.

The API defintion:

[System.CLSCompliant(false)]
public String (char* value);

A snippet of the API documentation:

Parameters

value Char*

A pointer to a null-terminated array of Unicode characters.


Is the declaration char* singleChar a pointer to a single char? The pointer docs example seems to say so.

So, why/how can it also be a pointer to an array? Why isn't the parameter type char[]*?

3
  • 1
    A pointer to an array is always a pointer to it's first element Commented Jan 3, 2021 at 19:00
  • And in this case the "array" (in truth a region of contiguous memory) is terminated by the null-terminator (the char with code 0) Commented Jan 3, 2021 at 19:07
  • 1
    The more correct description would be "a pointer to a null-terminated sequence of Unicode characters", but the term array is often used, even if incorrecttly... fixed (char* pch = "Hello world") { string str2 = new String(pch + 5); } few would say that pch + 5 is an array for example Commented Jan 3, 2021 at 19:12

1 Answer 1

3

A char[]* in C# is technically not possible because managed types (in this case char[]) cannot be pointers, the more correct would be char**. This is a little confusing having a pointer to a pointer, but think of it as nothing more than an array of char arrays.

A pointer in unsafe C# code is simply a reference to a region of memory. In the C language, char arrays are generally null-terminated (byte value of 0) using continuous blocks of memory for the strings. The same applies in C#, the char* is simply a pointer to a continuous block of memory of char type.

Example:

Memory address 0x10000000 : h
Memory address 0x10000002 : e
Memory address 0x10000004 : l
Memory address 0x10000006 : l
Memory address 0x10000008 : o
Memory address 0x1000000A : \0

In C#, you could have char* ptr = (char*)0x10000000 - and the memory would point to the chars h, e, l, l, o, \0.

You can convert a single C# array to a char* using the fixed keyword, which pins the char array down, preventing garbage collection or memory movement.

char[] chars = new char[64];
// fill chars with whatever
fixed (char* charPtr = chars)
{
}

chars in the above example could also be a string.

Hope some of this info is useful.

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.