0

how can i convert 1 dimension to 2 dimensional's matrix addressing and 1 d block addressing with pointer arithmetic in c programming language.

can anybody help please and thanks in advance:)

0

3 Answers 3

1

Suppose you want a 10x15 matrix (10 rows, 15 columns), for allocating memory:

int numRows = 10;
int numColumns = 15;
int *matrix = malloc(sizeof(int) * numRows * numColumns);

To access any element, multiply the desired row by the number of columns and add the column number:

//access row 3, column 5:
int value = matrix(3 * numColumns + 5);

Thats it.

0
int** matrix = malloc(sizeof(int*) * COLUMN_SIZE);
matrix[0] = malloc(sizeof(int) * COLUMN_SIZE * ROW_SIZE);

int* temp = matrix[0];
for (int i=1; i < COLUMN_SIZE; i++)
{
    matrix[i] = temp;
    temp += ROW_SIZE;
}

Now you'll have a linear array in matrix[0] that can also be addressed using either a linear index like matrix[0][INDEX] where index is between 0 and (COLUMN_SIZE * ROW_SIZE), or you can address it using matrix[COLUMN_INDEX][ROW_INDEX].

0
0

When the linear 1d index is called index and the 2d indexes row and col, the formula to transfer between them is

index = row * (MAX_ELEMENTS_PER_ROW) + col;

and the other direction

row = index / MAX_ELEMENTS_PER_ROW;
col = index % MAX_ELEMENTS_PER_ROW;

The pointer arithmetic is done by the + on a pointer and [] operator.

The actual coding I give to you as homework ;-).

Not the answer you're looking for? Browse other questions tagged or ask your own question.