Advice??

Hello, i just wanted some input from professionals on whether or not my code is efficient or proper. its a simple program using pointers and dynamic memory allocation, and using functions. It outputs and compiles exactly how i wanted it to, i just wanted insight if its proper? also i would like to know if im using
1
2
delete[] dArray;
	dArray = NULL; 
correctly in the right place. i didnt know if i should use it in main() or in one of my function definitions.

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
51
52
53
54
55
56
57
  #include <iostream>

using namespace std;


void fillArray(int*, int&);

void printArray(const int*, int);

const int CAPACITY = 1000;

int main()
{

	int *dArray;
	dArray = new int[CAPACITY];
	int numOfElements = 0;

	fillArray(dArray, numOfElements);
	printArray(dArray, numOfElements);

	delete[] dArray;
	dArray = NULL;

	cout << "\n\n";
	system("PAUSE");
	return 0;
}

void fillArray(int *p_array, int& numOfElements)
{
	int index = 0, value;

	cout << "Please type in values(-1 to stop, limit is 1000): ";
	cin >> value;

	while ((value != -1) && (index < CAPACITY))
	{
		numOfElements++;
		p_array[index] = value;
		index++;
		cin >> value;
	}

	
}

void printArray(const int *p_array, int numOfElements)
{

	cout << "Array: ";

	for (int i = 0; i < numOfElements; i++)
	{
		cout << p_array[i] << " ";
	}
}
Everything looks fine, delete is in right place: no memory leaks, no invalid accesses.
Thank you!
For your fillArray and printArray functions I would be consistent on whether or not I passed the array size by value or reference. Since the parameter is an int, I'd probably just go with pass by value for both. So instead of
void fillArray(int*, int&); I'd say void fillArray(int*, int); and update the function definitions accordingly.

EDIT: Misinterpreted the purpose of the "numberOfElements" parameter; assumed it was used for bounds checking

If you wanted to go nuts on your const correctness, you could const both the data you're pointing at and the pointer itself.
1
2
void fillArray(int* const, int);
void printArray(const int* const, int);


https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const
Last edited on
instead of void fillArray(int*, int&); I'd say void fillArray(int*, int); and update the function definitions accordingly.
...and break code because it does change value of passed variable
f you wanted to go nuts on your const correctness, you could const both the data you're pointing at and the pointer itself.

void fillArray(int* const, int);
void printArray(const int* const, int);
Making pointer function parameters const does not actually provide any benefit.
I think its probably good to get in the habit of using const where you can ( i.e., const pointers, pointers to const or both). It just seems like neater code.
Topic archived. No new replies allowed.