Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess a 1D array as a 2D array in C++
    primarykey
    data
    text
    <p>This has bothered me for a while. A lot of times I find myself making a large buffer to hold a "maximum" amount of data. This helps me avoid dynamically allocating and deallocating a buffer each time the size of the next data set changes. </p> <p>For instance say I have an array that is way too large for its actual useful size, but I know the length of the useful data.</p> <pre><code>int amountOfData = 9; char data1D[100] = some data that is only 9 bytes long stored in a 100 byte array </code></pre> <p>Lets say I have an algorithm I want to run on this data set that uses 2D array indexing. So I want to be able to access the data as follows:</p> <pre><code>cout &lt;&lt; "I am accessing this data as a 2D array: " &lt;&lt; data1D[0][1] &lt;&lt; endl; </code></pre> <p>Lets say for this algorithm I know that the xlength and ylength of the 2D array are going to be:</p> <pre><code>int xlength = 3; int ylength = 3; </code></pre> <p>for this iteration, because <code>amountOfData = 9</code>. However, the lengths may be different for the next iteration. Ie. they could be <code>xlength = 4</code> and <code>ylength = 4</code> given <code>amountOfData = 16</code>.</p> <p>I want to do some kind of casting that allows me cast the 1D array using 2D array indexing. I know how long my initial 1D length is, which tells me how long my 2D <code>xlength</code> and <code>ylength</code> are, so this should be easy to do without using <code>new</code> or <code>malloc</code> as long as the initial 100 bytes is long enough to hold any useful data set to me.</p> <p>I realize that:</p> <pre><code>char** data2d = (char**) data1D; </code></pre> <p>will not work because the compiler doesn't know the size of the second dimension. But I will know what it is at runtime!</p> <p>What is the underlying reason for this being the way it is? Are there any workarounds? Am I missing anything?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload