des*_*scf 2 c# c++ arrays pointers
下面是一个Win32控制台应用程序过程,演示了各种指针对数组的依赖性.通过例如取消注释标记为"// uncomment ..."的行来更改原始数组(模型)中的值会导致输出发生更改.我的问题是如何在C#托管代码环境中获取或模仿这种行为(即不使用不安全和指针)?
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float model[100];
for(int i = 0; i < 100; i++) { model[i] = i; }
// uncomment these to alter the results
//model[5] = 5000;
//model[20] = 20000;
//model[38] = 38000;
static const int componentCount = 5;
float* coefs = model; // coefs points to model[0]
float* mean = coefs + componentCount; // mean points to model[0 + componentCount] == model[5]
float* cov = mean + 3*componentCount; // cov points to model[0 + componentCount + 3*componentCount] == model[20]
int ci = 2;
float* c = cov + 9*ci; // c points to model[0 + componentCount + 3*componentCount + 9*ci] == model[38]
int i = 0;
cout <<"model : "<< model[i] << endl; // 0
cout <<"coefs : "<< coefs[i] << endl; // 0
cout <<"mean : "<< mean[i] << endl; // 5 (or 5000)
cout <<"cov : "<< cov[i] << endl; // 20 (or 20000)
cout <<"ci : "<< ci << endl; // 2
cout <<"c : "<< c[i] << endl; // 38 (or 38000)
cin.get(); }
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 14
你可以在没有不安全代码的情况下在C#中做同样的事情:
struct ArrayPointer<T>
{
private T[] array;
private int offset;
public ArrayPointer(T[] array) : this(array, 0)
{
}
private ArrayPointer(T[] array, int offset)
{
Debug.Assert(array != null);
Debug.Assert(offset >= 0);
Debug.Assert(offset < array.Length);
this.array = array;
this.offset = offset;
}
public static ArrayPointer<T> operator+(ArrayPointer<T> p1, int p2)
{
return new ArrayPointer<T>(p1.array, p1.offset + p2);
}
Run Code Online (Sandbox Code Playgroud)
等等.定义加法,减法,递增,递减,比较,索引,数组转换等运算符.然后你可以说:
int[] arr = whatever;
ArrayPointer<int> pointer = arr;
pointer+=2;
pointer--;
int x = pointer[3];
Run Code Online (Sandbox Code Playgroud)
等等.
这种方法有很多不错的特性.例如,如果您在p1和p2是指向不同数组内部的指针时比较p1> p2,则可以执行调试断言.这几乎总是C中的一个错误,但很难抓住.