Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

optimal usage of dynamicly allocated two-dimensional array

I have a two-dimensional array, which needs to be allocated dynamicly, so i wrote this:

int * array;
array = malloc((sizeA * sizeB) * sizeof(int));

It’s basicly an one-dimensional array, which acts like it’s a two-dimensional one. I’m accessing it like the following:

for(int y = 0; y <= sizeA; y++){
   for(int x = 0; x <= sizeB; x++){
      array[x * y] = /* some stuff */;
   }
}

I thought everything is fine to write it like that, but in some cases this would not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Case 1: x * y has the same result multiple times

x = 3, y = 2

x * y = 6

x = 2, y = 3

x * y = 6, aswell

Meaning some values get overwritten and get lost. But there is also another case, which leads to issues.

Case 2: primary number out of range of sizeA or sizeB

Some values can’t be used, because primary numbers can only be the result of the multiplication of the number itself and 1. So, while some values in my array get overwritten, some others dont even get used.

What can I do to prevent this from happening?

>Solution :

You need to first multiply the column size by row the number, then add the column number.

for(int y = 0; y < sizeA; y++){
   for(int x = 0; x < sizeB; x++){
      array[x + y * sizeB] = /* some stuff */;
   }
}

Also, you want to use < instead of <= so you don’t have an off-by-one error.

Here’s a graphical view to give you a better idea of how this is working:

  |  0 |  1 |  2 |  3 |
-----------------------
0 |  0 |  1 |  2 |  3 |
-----------------------
1 |  4 |  5 |  6 |  7 |
-----------------------
2 |  8 |  9 | 10 | 11 |
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading