如何使用C#中的指针访问数组元素?
在C#中,数组名称和指向与数组数据相同的数据类型的指针不是相同的变量类型。例如,int*p和int[]p不是同一类型。您可以增加指针变量p的值,因为它在内存中不是固定的,但数组地址在内存中是固定的,因此您不能递增它。
这是一个例子-
示例
using System;
namespace UnsafeCodeApplication {
class TestPointer {
public unsafe static void Main() {
int[] list = {5, 25};
fixed(int *ptr = list)
/* let us have array address in pointer */
for ( int i = 0; i < 2; i++) {
Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
}
Console.ReadKey();
}
}
}输出结果
这是输出-
Address of list[0] = 31627168 Value of list[0] = 5 Address of list[1] = 31627172 Value of list[1] = 25
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短