【发布时间】:2011-05-16 22:59:59
【问题描述】:
下面是一个 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(); }
【问题讨论】:
-
您的意思是使用数组语法取消引用您的指针,还是存在您希望 i > 0 的情况(意味着超过平均值的值或其他什么?)
-
顺便说一句,你所做的就是所谓的“指针别名”。
-
i 可能不是 0,这只是示例。