aaa
aaa

Reputation: 435

Best solution to represent Data[i,j] in c?

There is a pseudocode that I want to implement in C. But I am in doubt on how to implement a part of it. The psuedocode is:

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

i and j, in qi and qj are subscripts.

how do I represent D[i,J] or S[i,j]. which data structure to use so that its simple and fast.

Upvotes: 2

Views: 167

Answers (3)

chux
chux

Reputation: 153447

After accept answer.

Depending on coding goals and platform, to get "simple and fast" using a pointer to pointer to a number may be faster then a 2-D array in C.

// 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();

Flexibility

The first data type is easy print(x), when the array size is fixed, but becomes challenging otherwise.

The 2nd data type is easy print(y, rows, columns), when the array size is variable and of course works well with fixed.

The 2nd data type also row swapping simply by swapping pointers.


So if code is using a fixed array size, use double x[MAX_ROW][MAX_COL], otherwise recommend double **y. YMMV

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

You can use something like

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

and then

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

Here D[i,j] and S[i,j] are represented by res1[10][10] and res2[10][10], respectively. These are called two-dimentional array.

Upvotes: 2

4rlekin
4rlekin

Reputation: 758

I guess struct will be your friend here depending on what you actually want to work with.
Struct would be fine if, say, pair of states creates some kind of entity. Otherwise You could use two-dimensional array.

Upvotes: 0

Related Questions