我有以下(不完整的)功能:
/* Populates char* name with the named location of the ith (flat) element
* of an array with ndim dimensions where the length of each dimension
* is already stored in the int* dim.
*
* name: a pointer to where the name should be populated
* n: the base name of the array
* dim: an int[] containing the length of each dimension
* ndim: length of the dim array
* i: name of the iteration variable being used
**/
void populateName(char *name, const char *n, int *dim, int ndim, const char *i) {
strcpy(name, n);
char *loc = (char*)(name + strlen(n));
char *curr;
for (int k = 0; k < ndim; k++) {
...
sprintf(loc, "[%s]", curr);
loc += strlen(loc);
}
}
for 循环中的“...”应该包含什么?例如,使用以下命令调用 populateName():
int dim[2] = {3, 4};
char name[1024];
populateName(name, "x", dim, 2, "i");
应该导致类似:
name = "x[i / 3][i % 4]"
或用于访问数组中第 i 个位置的其他有效名称,定义为:
int x[3][4];
上下文:我正在编写一个 C 程序,它生成 C 程序,这些程序根据用户定义的数据类型和 IDL 中编写的规则过滤大量数据。
编辑:返回包含数组中位置/坐标的元组的python函数可能会让我朝着正确的方向前进。特别是以下数组应使每个元素与其在数组中的平面位置相对应(在此处使用 pylab):
In [14]: x
Out[14]:
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]]])
In [15]: x.flat.copy()
Out[15]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])