0

I have a jagged 2D array, the rows aren't all the same length:

int sizes[100];
//init sizes

unsigned char *p = [100];

for(unsigned int i = 0; i < 10; i++)
{
    p[i] = (unsigned char*)malloc(sizeof(char)*sizes[i]);
    for(unsigned int j = 0; j < sizes[i]; j++)
        p[i] = j;
}

I use the array like this:

p[x][y]

How can I simulate this array to 1D?

Mat
  • 202,337
  • 40
  • 393
  • 406
Blazer
  • 235
  • 2
  • 9

3 Answers3

2

If you're looking for a way to map a two dimensional array onto a one dimensional space, then try...

int sizes[width*height];
void setPoint(int x, int y, int val) {
  sizes[x*width + y] = val;
}

Notably the x*width + y indexing will give you the appropriate element in the one dimensional array.

Lawrence Jones
  • 955
  • 6
  • 14
2

I assume that if you want to access your "2D array" as a one D matrix, you expect that as you increment your index by 1, you access the next element in the array (and will automatically go to the next line when you run off the edge). The right way to do this is by changing the way you allocate the array. I'll try to show how this is done - this is just C, not C++. It's probably more appropriate since you were using malloc anyway. I am also thinking that you have a pretty serious error in your code, in that you are creating a char * pointer p, yet expect to use it in

p[x][y];

for which you would need a char **, obviously. Let's try to make code that would do what you want:

int sizes[100];
//init sizes

unsigned char *p[100];  // without the == sign we create an array of 100 pointers
unsigned char *bigP;   // the master pointer

int totalLength = 0;

int ii;
for(ii=0; ii<100; ii++) totalLength += sizes[ii];

bigP = malloc(sizeof(char) * totalLength);

int offset = 0;

// make pointers p point to places along this big memory block:
for(ii = 0; ii < 100; ii++) {
  p[ii] = bigP + offset;
  offset += sizes[ii];
}

Now you can either address your array with

p[x][y];

or with

bigP[z];

where z can go from 0 to the maximum number of elements. Of course, in the process you don't know (when you are using the "1D" paradigm) in what row/column of the jagged array you are - you can't know that if you are truly in one dimension.

The key here is that the memory is allocated as a single contiguous block, and the pointers p are pointing to places in that block. This means you MUST NOT FREE p. You must only ever free bigP.

I hope this makes sense.

Floris
  • 45,857
  • 6
  • 70
  • 122
1

Unless it is homework just download boost and use Boost.Matrix.

Öö Tiib
  • 10,809
  • 25
  • 44