Note that there are some explanatory texts on larger screens.

plurals
  1. POAllocate chunk of memory for array of structs
    primarykey
    data
    text
    <p>I need an array of this struct allocated in one solid chunk of memory. The length of "char *extension" and "char *type" are not known at compile time.</p> <pre><code>struct MIMETYPE { char *extension; char *type; }; </code></pre> <p>If I used the "new" operator to initialize each element by itself, the memory may be scattered. This is how I tried to allocate a single contiguous block of memory for it:</p> <pre><code>//numTypes = total elements of array //maxExtension and maxType are the needed lengths for the (char*) in the struct //std::string ext, type; unsigned int size = (maxExtension+1 + maxType+1) * numTypes; mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size); </code></pre> <p>But, when I try to load the data in like this, the data is all out of order and scattered when I try to access it later.</p> <pre><code>for(unsigned int i = 0; i &lt; numTypes; i++) { //get data from file getline(fin, line); stringstream parser.str(line); parser &gt;&gt; ext &gt;&gt; type; //point the pointers at a spot in the memory that I allocated mimeTypes[i].extension = (char*)(&amp;mimeTypes[i]); mimeTypes[i].type = (char*)((&amp;mimeTypes[i]) + maxExtension); //copy the data into the elements strcpy(mimeTypes[i].extension, ext.c_str()); strcpy(mimeTypes[i].type, type.c_str()); } </code></pre> <p>can anyone help me out?</p> <p>EDIT:</p> <pre><code>unsigned int size = (maxExtension+1 + maxType+1); mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size * numTypes); for(unsigned int i = 0; i &lt; numTypes; i++) strcpy((char*)(mimeTypes + (i*size)), ext.c_str()); strcpy((char*)(mimeTypes + (i*size) + (maxExtension+1)), type.c_str()); </code></pre>
    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.
    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