Dynamic Array Not Properly Allocating Memory

This code is supposed to iterate through a dynamically allocated array of 5 elements in size and store the user's input into the array in the next slot. But when I determine the size of the array I am only getting it to ever equal one. I even changed the constant INITIAL_SIZE to the literal constant of 5 with the same results. What am I doing wrong?

I have provided first the code that defines the dynamic array and then the code that reads in the values. They are two separate functions so the problem may be my passing the pointer to the dynamic array but I'm not for sure. I'm sorry about the comment formatting it came out messed up and when I tried to fix it it just made it worse.

Declares the dynamic array:
 
int* pNumericalInput = new int[INITIAL_SIZE];


Retrieves user input:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void getInput(int* pDataInputArray)
{
	cout << "Input positive integer values one at a"//Ask the user to input values and
		 << " time. A negative value will stop "	//indicate that a negative value
		 << "input." << endl;						//terminates the program.

	short input;									//Will hold the user's inputted value.

	do												//Run through the process at least 
	{												//once to get user input.
		short counter = 0;							//This is the counter of inputted values.
		cin >> input;								//Store the input to input.
		*(pDataInputArray + counter) = input;		//Set the value in the array equal to input.
		counter++;									//Increase the value counter.

		short mod5;									//Will hold the value of counter % 5.
		mod5 = counter % 5;

		if (mod5 = 0)								//Since the array is multiples of 5 in 
		{											//size, anytime 5 values have been entered,
													//the size of the array needs increased.
			pDataInputArray = increaseArraySize(pDataInputArray);
		}

	} while (input >= 0);							//if the input is < 0 terminate the loop.
}
Hi
1
2
3
do	
{											
	short counter = 0;


Your variable, counter, is a local variable allocated on the stack. So it will expire at the end of its enclosing block/scope. In other words, each time your loop executes, this variable is redeclared and its value re-initialized to 0. Any index variables need to be declared outside of your do ... while loop.
E.g.
1
2
3
4
short counter = 0;
do
{
    // etc. 

Same thing with your mod5 variable.
Also, any reason you're using shorts rather than ints?
Regards, keineahnung

*EDIT*
Sorry mod5 is OK:)
Last edited on
First, I use short because our instructor wants us to venture away from int when the number does not require that amount of memory to store ever so I do it to appease him.

I have fixed the counter variable situation, but now the code executes and gives me a runtime error. I added this line of code of creating the dynamic array and got the result of 1.
1
2
int size = sizeof(pNumericalInput)/sizeof(int);
cout << size << endl;

This should result in 5 if I'm not mistaken.
Nope. sizeof(a_pointer) gives you the size of a pointer (which is typcially 4). pNumericalInput is a pointer, it is not an array.

sizeof is a crappy way to get array sizes anyway. You should put it out of your mind -- it shouldn't be used for that purpose.

There is no way to get the size of the array pointed to by pNumericalInput alone. You will need to pass the size of the array as another paramter to this function.

That is, you would do this:

void getInput(int* pDataInputArray, int nDataInputSize)

And then supply both when you call the function.


I use short because our instructor wants us to venture away from int when the number does not require that amount of memory to store ever so I do it to appease him.


Do what your instructor says. But blech...

An extra 2 bytes of memory is nothing. Particularly on stack space where it doesn't make a difference how much you use unless you use all of it.

Furthermore "natural" memory accesses are often faster. On 32 bit systems, a 32-bit variable (int) is likely to be faster than a 16-bit one (short).

But in either case the differences are very very minor. To the point where is practically doesn't matter which way you do it because you don't see a difference in the end result either way. Really... the thing you're most likely to notice is accidentally overflowing a short.
A new operator can help us here. The sizeof operator produces an integer value of type size_t
that gives the number of bytes occupied by its operand, where size_t is a type defi ned by the
standard library. Many standard library functions return a value of type size_t , and the size_t
type is defi ned within the standard library using a typedef statement to be equivalent to one of the
fundamental types, usually unsigned int . The reason for using size_t rather than a fundamental
type directly is that it allows fl exibility in what the actual type is in different C++ implementations.
The C++ standard permits the range of values accommodated by a fundamental type to vary, to
make the best of a given hardware architecture, and size_t can be defi ned to be the equivalent of
the most suitable fundamental type in the current machine environment.
Look at this statement that refers to the variable dice from the previous example:
cout < < sizeof dice;
The value of the expression sizeof dice is 4 because dice was declared as type int and therefore
occupies 4 bytes. Thus this statement outputs the value 4 .
The sizeof operator can be applied to an element in an array or to the whole array. When the
operator is applied to an array name by itself, it produces the number of bytes occupied by the whole
array, whereas when it is applied to a single element with the appropriate index value or values, it
results in the number of bytes occupied by that element. Thus, in the last example, you could output
the number of elements in the pstr array with the expression:
cout < < (sizeof pstr)/(sizeof pstr[0]);
The expression (sizeof pstr)/(sizeof pstr[0]) divides the number of bytes occupied by the
whole pointer array, by the number of bytes occupied by the fi rst element of the array. Because each
element in the array occupies the same amount of memory, the result is the number of elements in
the array.

That is quoted from Ivor Horton's Beginning Visual C++ 2010 published by Wrox. That is where I got the idea.

I agree with you on the use of short and int and int is clearly the better choice but I can see that there, in some really strange (and quite possibly very inefficient coding in other ways) be a use for short, but I think most of the time it is trivial.

Now back to the problem at hand. It still will not let me write to the various blocks of memory that I have dynamically assigned. To read the values in I shouldn't need to pass the size because the size will increase after every 5th number is input to accomadate for five more numbers. I can't even get it to accept the first five numbers. In the output results function if I change the loop (the function is below) to iterate manually 4 times (for the 4 values and disregard the fifth negative number) I get -17891602 4 times in a row. Obviously this is just garbage left over in memory that is being displayed so it isn't writing the values I've supplied to it to the console (in this example I supplied 1, 2, 3, 4, -5).

The outputResults function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void outputResults(const int* pDataArray)
{
	int arraySize = sizeof(pDataArray)/sizeof(int);	//To know how many iterations there 
													//are going to be we must determine
													//the size of the array.
	short iterationCounter = 1;						//This is initially set to one so that
													//it can easily be passed to the 
													//function calculateAverage() as the 
													//second parameter of how many nums.
													//there are.
	while (iterationCounter <= (/*arraySize - 1*/4))		//Since the array will store the last
	{												//value (or neg. value) we will want
													//to exclude this last value.
		int mod5 = iterationCounter % 5;
		if (mod5 == 0) cout << endl;
		int value = *(pDataArray + (iterationCounter - 1));//The minus 1 is used here
													//because indexes start at zero, not
													//at one which is the value that 
													//iteration counter is initially set
													//to.
		cout << value << ' ';
		iterationCounter++;							//Since we have added a value, we will
	}												//increment iteration counter in order 
													//to access the next value on the next
													//iteration of the loop.

	system ("PAUSE");
}


I don't understand why it isn't writing the values to memory like it should and why doesn't it seem to be allocating the memory for the array?
closed account (DSLq5Di1)
@ddwinters45
As Disch mentioned, using sizeof on a pointer will yield the size of the pointer.
http://ideone.com/keKRt
Hi
Maybe the problem lies with the other part of your code that's getting the input?
This seems a very laboured way of outputting the contents of an array. You'd normally pass in the size of the array as a second parameter to the function.
E.g.
void outputResults( int* array, int n )

If you don't want to output the final (negative) value, just set n to 4.
Then you get:
1
2
3
4
5
for ( int i = 0; i < n; ++i )
{
    std::cout << array[i] << " ";
} // for
std::cout << "\n";


And array iterators should start at 0, not 1. If that's a problem for another function (you're worried about division by zero errors?), then it'd maybe be better to test for that in your other function.

Last edited on
I wasn't arguing with Disch, only stating what I read in the book which stated contrary to what he said.

I am accomadating for the indexes starting at 0 with the - 1. That is the point of that being there. I commented out that part of code and instead of using the sizeof operator manually put a 4 in for testing purposes. The result was as I described in my last post with the garbage that was left in memory. The problem here is getting the values into the array.
closed account (DSLq5Di1)
It's difficult to provide further feedback without seeing more of your code and the context it is used in.
Topic archived. No new replies allowed.