如何使用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 教师闺蜜祝福语简短