Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does the debugger show only one element from my array pointer?
    primarykey
    data
    text
    <p>First off: I know that <code>new</code> is the C++ way of doing this. I am simply showing that there is more than one way to reproduce this error, and both are incredibly frustrating.</p> <p>I have two forms of this source file. I'm trying to debug yet another programming assignment, but I'm not asking for help on that. Basically, I'm trying to re-implement <code>set</code> as a class with fields for size and a pointer to an <code>int</code> array. Here's the code using <code>new</code>:</p> <p>testnew.cpp</p> <pre><code>int main() { int size = 1; int *elements = new int[size]; elements[0] = 0; size++; int * temp = new int[size]; for (int i = 0; i &lt; (size - 1); i++) { temp[i] = elements[i]; } delete[] elements; temp[size] = size; elements = temp; elements[1] = 1; delete[] elements; } </code></pre> <p>and again, using the less-preferable <code>alloc</code> functions:</p> <p>testalloc.cpp</p> <pre><code>int main() { int size = 1; int * elements = (int *) malloc(sizeof(int) * size); elements[0] = 0; size++; elements =(int *) realloc(elements,size * sizeof(int)); elements[1] = 1; free(elements); } </code></pre> <p>In both cases, my goal is to create an array, and then append to it. However, in both cases, after building and running it in Visual Studio 2010, <strong>the array is not grown at all, and only has 1 "slot" for my items to go into</strong>. In VS's debugger, I have watches on the <code>elements</code> array pointer; attached is a screenshot. It is the same for both versions of the code.</p> <p><img src="https://i.stack.imgur.com/CRtuU.jpg" alt="My watches at the end of the program"> </p> <p>-- the breakpoint is at the <code>delete[]</code>/<code>free()</code> call.</p> <p>Seriously, what am I doing wrong? This has to be a logic error, and I've combed through a quarter dozen examples of both <code>malloc</code>/<code>realloc</code> and <code>new</code>, and read and re-read my textbook, and I can't see what's wrong! </p> <p>I feel like I should have a line that splits the allocated memory into an array, but doesn't the <code>new int[]</code> call do that?</p>
    singulars
    1. This table or related slice is empty.
    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