【问题标题】:Can you make sense of this C pointer code?你能理解这个 C 指针代码吗?
【发布时间】:2010-12-01 11:19:15
【问题描述】:
我有这个 C 代码的 sn-p,它以一种非常令人困惑的方式使用指针。
// We first point to a specific location within an array..
double* h = &H[9*i];
int line1 = 2*n*i;
int line2 = line1+6;
// ..and then access elements using that pointer, somehow..
V[line1+0]=h[0]*h[1];
V[line1+1]=h[0]*h[4] + h[3]*h[1];
这里发生了什么?如何在 C# 中编写等效的东西?
【问题讨论】:
标签:
c#
c
arrays
visual-c++
pointers
【解决方案1】:
您实际上并没有在 C# 中编写等效的东西,因为那里没有指针(调用unsafe 代码除外)- 要从 C# 数组中获取元素,您需要数组 ref 和索引,并且你索引到数组中。
当然,您可以对 C 数组执行相同的操作。我们将 C 指针算术转换为 C 数组索引:
int h_index = 9 * i;
int line1 = 2 * n * i;
int line2 = line1 + 6;
V[line1 + 0] = H[h_index] * H[h_index + 1];
V[line1 + 1] = H[h_index] * H[h_index + 4] + H[h_index + 3] * H[h_index + 1];
然后我们有了一些可以在 C# 中逐字使用的东西。
【解决方案2】:
&H[9*i] == (H + 9*i),因此您可以将h[x] 的使用替换为H[9*i+x]。其余的应该很简单。