在c中表示Data [i,j]的最佳解决方案?

时间:2014-10-27 11:48:37

标签: c data-structures

我想在C中实现一个伪代码。但是我对如何实现它的一部分存在疑问。伪造的代码是:

for every pair of states qi, and qj, i<j, do
    D[i,j] := 0
    S[i,j] := notzero
end for

ijqiqj是下标。

如何代表D[i,J]S[i,j]。使用哪种数据结构使其简单快速。

3 个答案:

答案 0 :(得分:2)

您可以使用类似

的内容
int length= 10;
int i =0, j= 0;
int res1[10][10] = {0, }; //index is based on "length" value
int res2[10][10] = {0, }; //index is based on "length" value

然后

for (i =0; i < length; i++)
{
    for (j =0; j < length; j++)
    {
        res1[i][j] = 0;
        res2[i][j] = 1;//notzero
    }
}

此处D[i,j]S[i,j]分别由res1[10][10]res2[10][10]表示。这些被称为二维数组

答案 1 :(得分:0)

我想struct将成为您的朋友,具体取决于您实际想要使用的内容 如果,例如,一对国家创造某种实体,那么结构将是好的。 否则你可以使用二维数组。

答案 2 :(得分:0)

接受回答后。

根据编码目标和平台,使用pointer to pointer to a number获得“简单快速”可能比使用2-D array更快。

// 2-D array
double x[MAX_ROW][MAX_COL];

// Code computes the address in `x`, often involving a i*MAX_COL, if not in a loop.
// Slower when multiplication is expensive and random array access occurs.
x[i][j] = f();

// pointer to pointer of double
double **y = calloc(MAX_ROW, sizeof *y);
for (i=0; i<MAX_ROW; i++) y[i] = calloc(MAX_COL, sizeof *(y[i]));

// Code computes the address in `y` by a lookup of y[i]
y[i][j] = f();

灵活性

当数组大小固定时,第一种数据类型很容易print(x),否则会变得具有挑战性。

第二种数据类型很简单print(y, rows, columns),当数组大小可变时,当然适用于固定数据。

第二种数据类型也只是通过交换指针进行交换。

因此,如果代码使用固定数组大小,请使用double x[MAX_ROW][MAX_COL],否则建议使用double **yYMMV