关于C# 使用指针
错误代码;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console菜鸟教程95
{
class Program
{
public struct programming
{
public float constant;
public char pointer;
}
static void Main(string[] args)
{
unsafe
{
char *pointer;//c#中定义指针变量只能在局部变量以及不安全上下文中
programming variable = new programming();
char[] s = "菜鸟教程:http://www.runoob.com";
variable.constant = 1.23f;
pointer =&s;
variable.pointer = *pointer;
Console.WriteLine("{0}\n", variable.constant);
Console.WriteLine("{0}\n",variable.pointer);
Console.ReadKey();
}
//疑问:c中的char string[]在c#中怎么实现,需要实例化吗?
// 为什么输出的会是菜,指针不应该获取的是地址吗?
// 我想将s数据类型转化为string,指针也转为string但是错误 CS0208 无法获取托管类型(“string”)的地址和大小,或者声明指向它的指针 Console菜鸟教程95 C: \Users\liduoxiang\Desktop\C#\c#100实例题\Console菜鸟教程95\Program.cs 27 活动
}
}
}
修改后的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _95
{
class Program
{
struct programming
{
public float constant;
public unsafe char*[] pointer;
}
static unsafe void Main(string[] args)
{
programming variable = new programming();
char[] str = ("菜鸟教程:http://www.runoob.com").ToCharArray();
variable.pointer = new char*[str.Length];
for (int i = 0; i < str.Length; i++)
{
fixed (char* pointer = &str[i])
{
variable.pointer[i] = pointer;
}
}
variable.constant = 1.23f;
Console.WriteLine("{0}", variable.constant);
foreach (var item in variable.pointer)
{
Console.Write(*item);
}
Console.ReadKey();
}
}
}
**
了解一下C#指针中托管类型和非托管类型的差异
**
/*使用指针访问数组元素*/
using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe static void Main()
{
int[] list = { 10, 100, 1000 };
//因为int* ptr 和int[]list是不同类型的,
//指针ptr在内存中是不固定
//而数组地址是固定的
//所以要用fixed关键字来固定指针
fixed(int* ptr = list) //固定指针
for(int i = 0; i<3; i++)
{
Console.WriteLine("Address of list[{0}] = {1}", i, (int)(ptr + i));
Console.WriteLine("value of list[{0}] = {1}", i, *(ptr + i));
}
Console.ReadKey();
}
}
}