Pointer Function

Down below, there is a function called at line 15, "*growArray ()". However, I'm not sure what the difference between a regular function, without the "*" and this function here. Any suggestions?

Also, when the code declares at line 31, "int *p_values = new int[size]" and "int size = 10", does that mean the pointer, which has the name, p_values, is holding the first address of the array with a size 10? And allocates each memory in the address to hold the size of an integer?

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
44
45
46
47
48
49
50
#include <iostream>
using namespace std; 

void printArray (int *p_values, int size, int elements_set)
{
	cout << "The total size of the array is: " << size << endl;
	cout << "Number of slots set so far: " << elements_set << endl;
	cout << "Values in the array: " << endl;
	for (int i = 0; i < elements_set; ++i)
	{
		cout << "p_values [" << i << "] = " << p_values[i] << endl;
	}
}

int *growArray (int *p_values, int *size)
{
	*size *= 2;
	int *p_new_values = new int [*size];
	for (int i = 0; i < *size; ++i)
	{
		p_new_values[i] = p_values[i];
	}
	delete [] p_values;
	return p_new_values;
}

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)
		{
			p_values = growArray(p_values, &size);
		}
		p_values[next_element] = val;
		next_element++;
		cout << "Current array values are: " << endl;
		printArray(p_values, size, next_element);
		cout << "Please enter a number (or 0 to exit): "; 
		cin >> val; 
	}
    return 0; 
}
Last edited on
I'm not sure what the difference between a regular function, without the "*" and this function here.

The * belongs to the int return type, not the function name. The spacing is a little misleading. int * means the function returns an int pointer. If you look at line 18, you will see p_new_values is an int pointer. That pointer is returned at line 24.

does that mean the pointer, which has the name, p_values, is holding the first address of the array with a size 10?

Yes

And allocates each memory in the address to hold the size of an integer?

I would not phrase it quite that way. The new allocates consecutive memory locations sufficient to hold 10 ints (typically 40 bytes). The base address of that memory area is assigned to the pointer p_values.




Last edited on
Topic archived. No new replies allowed.