Need help on Dynamic Memory Allocation

hello, i'm new to programming and i've been learning Jumping int C++. i've problem understanding why a pointer is used as a function name.
Secondly i do not get how the conditon if(size== next_element +1)
is met since next_element is initialised to zero and i dont know how it is incremented to meet this condition.
finally i'll be very greatful if the whole code is commented out for me(i know it is not encouraged) since i have been stuck trying to grasp this code for about a month now.other advices are welcomed
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 #include <iostream>

using namespace std;

int *growArray (int* p_values, int cur_size);

int main ()
{

int next_element = 0;
int size = 10;

int *p_values = new int[ size ];
int val;

cout << "Please enter a number: ";
cin >> val;

while ( val > 0 )
{
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, size );
}
p_values[ next_element ] = val;

cout << "Please enter a number (or 0 to exit): ";

cin >> val;
}
}

int *growArray (int* p_values, int cur_size)
{
int *p_new_values = new int[ cur_size * 2 ];
for ( int i = 0; i < cur_size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete p_values;
return p_new_values;
}
int *growArray (int* p_values, int cur_size)
is not pointer to function, but function that returns int* (pointer to int)

if(size== next_element +1)
can be written as:
if( size== (next_element +1) )
see: http://en.cppreference.com/w/cpp/language/operator_precedence

if you dont understand how does this code work, set breakpoint and step by step whole program, while watching how variables are changing.
thnks for making my first problem clear to me.
for the second part , i mean to say how does
"next_element"
in
p_values[ next_element ] = val;
get increment that it meets the condition
if ( size == next_element + 1 )
next_element is always 0 here, so that if will never be true.
Last edited on
Topic archived. No new replies allowed.