Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a string literal to a char*

Tags:

c#

unsafe

just messing around with the unsafe side of c#

unsafe {
    char* m = stackalloc char[3+1];
    m[0] = 'A';
    m[1] = 'B';
    m[2] = 'C';
    m[3] = '\0';
    for (char* c = m; *c != '\0'; c++) {
        Console.WriteLine(*c);
    }
    Console.ReadLine();
}

Is it possible to assign a string literal to a char pointer just like in C or do I have to do it as in the above snippet?

like image 417
FPGA Avatar asked Jun 05 '15 13:06

FPGA


1 Answers

You could do something like this:

string m = "abc";
unsafe 
{
    fixed (char* pm = m)
    {               

    }
}

fixed sets a pointer to a managed variable and "pins" that variable so the GC won't clean it up. https://msdn.microsoft.com/en-US/library/f58wzh21(v=vs.80).aspx

like image 158
edtheprogrammerguy Avatar answered Oct 29 '22 17:10

edtheprogrammerguy