如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP