• C

retrieve matrix from a linear array

Hi, i want to retrieve a 2D array from a linear array data

How do i do it? :)
Who is Participating?
Raheman M. AbdulSenior Infrastructure Support Analyst & Systems DeveloperCommented:
int linearArray[]={1,2,3,4,5,6,7,8,9,10, .............. };

const int rows=10;
const int columns=5;
int matrix2D[rows][columns];
int r=0;
int c=0;

for (int i=0;i<linearArray.length;i++)

    //get the next element of linear array into the next cell of 2D array


Hope this helps
You need to know the dimensions of the 2D array first, and those could be constants.
Then you convert x & y to linear dimensions.

#define X_DIM 4
#define Y_DIM 4

int linear[X_DIM * Y_DIM];

So equivalent of matrix[x][y] would be:

linear[x + y * X_DIM]

How was the 2D array stored in the linear array data?
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

If you know the size of both arrays, and these arrays are fixed, you can do some neat shortcutting
(taking the necessary tests and saftey checks first, of course)
typedef struct 
   int row[10];
   int col[5];

int array[] = {1,2,3,,9,10,11,..........};

// for a quick copy of the flat array into the 2D array
memcpy( &intArray, array, sizeof( array))

Open in new window

> Hi, i want to retrieve a 2D array from a linear array data
> How do i do it?
Before you dive into writing code for this, tell us, whether you can do this manually?
If so, can you take an example and show us how you will do it?
Looking at your example, we can suggest you how to write the code.
VasconcelosAuthor Commented:
i already found a solution thanks to the first 2 answers, sorry for my delay :)
VasconcelosAuthor Commented:
thanks :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.