Array Count

How do I determine the number of elements in an array and how do I initialize double* jack_high if necessary?

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
 // C20.cpp
#include "std_lib_facilities.h"

double* get_from_jack(int* count);

int main()
{
	double h = -1.0;
	double* jack_high;
	int jack_count = 0;
	
	double* jack_data = get_from_jack(&jack_count);

	jack_count = sizeof(jack_data) / sizeof(jack_data[0]);

	for (int i = 0; i < jack_count; ++i)
		if (h < jack_data[i]) {
			jack_high = &jack_data[i];
			h = jack_data[i];
		}

	cout << "Jack's max: " << *jack_high << " h == " << h << endl;
	
	delete[] jack_data;

}


double* get_from_jack(int* count) {
	return new double[] { 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 };
}
Last edited on
Line 14 is not going to work. That works properly only for arrays. For pointer it will silently produce wrong result (either 0 or 1 depending on your machine).

There is no way to determine amount of elements in pointer to array. You need to keep count yourself.

1) remove line 14.
2) Write elements number to the variable count is pointing to in get_from_jack (Tht is why pointer to variable is passed)

For the future: safe way to get array size is this:
1
2
template<typename T, std::size_t Size>
std::size_t GetArrLength(T(&)[Size]) { return size; }
It will fail to compile instead of producing incorrect results.

Is this an assigment to learn about pointers, dynamic memory allocation and so on? Because if this is not, use proper containers who know their size.
Thank you very much MiiNiPaa. The coding is an assignment to learn about containers, starting with this program that was modified by me to understand what is going on.

Here's the final coding:
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
// C20.cpp
#include "std_lib_facilities.h"

double* get_from_jack(int* count);

int main()
{
	double h = -1.0;
	double* jack_high;
	int jack_count = 10;

	double* jack_data = get_from_jack(&jack_count);

	for (int i = 0; i < jack_count; ++i) {
		if (h < jack_data[i]) {
			jack_high = &jack_data[i];
			h = jack_data[i];
		}
	}

	cout << "jack_high = " << *jack_high << " h == " << h << endl;
	
	delete[] jack_data;

}


double* get_from_jack(int* count) {
	return new double[*count] { 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 };
}

Topic archived. No new replies allowed.