Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a way to free only a part of the dynamically allocated array in C\C++ (shrink existing array)?
    text
    copied!<p>In a program I allocate a huge multidimensional array, do some number-crunching, then only the first part of that array is of further interest and I'd like to free just a part of the array and continue to work with the data in the first part. I tried using realloc, but I am not sure whether this is the correct way, given I must preserve the data in the array and preferably avoid copying of that chunk in memory.</p> <pre><code>#include &lt;cstring&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; using namespace std; void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size); int main() { const int initial_size = 1024*1024*1024; char* my_array = static_cast&lt;char*&gt;(malloc(initial_size)); assert(my_array); int new_size; FillArrayThenTruncate(my_array, initial_size, &amp;new_size); for(int i = 0; i &lt; new_size; ++i) cout &lt;&lt; static_cast&lt;int&gt;(my_array[i]) &lt;&lt; endl; } void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size) { //do something with my_array: memset(my_array, 0, old_size); for(int i = 0; i &lt; 10; ++i) my_array[i] = i % 3; //cut the initial array *new_size = 10; void* new_array = realloc(my_array, *new_size); cout &lt;&lt; "Old array pointer: " &lt;&lt; static_cast&lt;void*&gt;(my_array) &lt;&lt; endl; cout &lt;&lt; "New array pointer: " &lt;&lt; new_array &lt;&lt; endl; my_array = static_cast&lt;char*&gt;(new_array); assert(my_array != NULL); } </code></pre> <p>UPDATE:<br> * Please do not bother to suggest to use STL. The question is about C array.<br> * Thanks to "R Samuel Klatchko" for pointing out the bug in the code above.</p>
 

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