How do I determine the size?

Hello,

How do I determine the size?

Thanks


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
#include <iostream>
using namespace std;

int* EvenOROdd(int myArray[], int length)
{
	int* p = new int[50];
	int k = 0;
	for (int i = 0; i < length; i++)
	{
		if (myArray[i] % 2 == 0)
		{
			p[k++] = myArray[i];
		}
	}
	int* newP = new int[k];
	for (int i = 0; i < k; i++)
	{
		newP[i] = p[i];
	}
	return newP;
}

int main()
{

	int array[10] = { 11,15,8,47,6,33,0,1,4,88 };

	int array2[10] = { 1,5,80,447,6141,3,8,1,25,89 };


	int* p1 = EvenOROdd(array, 10); // How do I determine the size?

	int* p2 = EvenOROdd(array2, 10); // How do I determine the size?

	for (int i = 0; i < length; i++) // We need the size of array (for p1)
	{
		cout << p1[i]<<" ";
	}

	for (int i = 0; i < length; i++) // We need the size of array (for p2)
	{
		cout << p2[i] << " ";

	}

	return 0;
}
The size is already a known, compile-time constant. So you might as well just make it a const int.

1
2
3
4
const int Size = 10;
int array[Size] = { ... };
int array2[Size] = { ... };
my_func(array, Size);


But you can do
1
2
3
	int array[10] = { 11,15,8,47,6,33,0,1,4,88 };
        cout <<  (sizeof(array)/sizeof(*array)) << '\n';
	my_func(array, sizeof(array)/sizeof(*array));
Last edited on
Thank you for your reply,
In line 35 and 40, I should determine the length.
The length for line 35 is 5 and for line 40 is 2. We need the size of the array.
Last edited on
You can't. C arrays don't have size. You need to return the size from the function.
its 10.
do the first block he said ^^^^^ there is no reason to 'compute' it with cryptic pointer math.
Shervan is now talking about how to get the size of the array that p1 and p2 point to. The answer is that you can't with your current setup. You could return a {pointer, length} pair from the function to preserve that information, or pass in the length as an "out" reference parameter.

PS: you have a blatant memory leak in your EvenOrOdd function. You should delete[] p before returning.
Last edited on
It looks like main is responsible for deletion in this design. But it needs to be in there somewhere.

I see .. yes, return the size is the best way to know, as you knew it when you called 'new'.
It looks like main is responsible for deletion in this design. But it needs to be in there somewhere.
The p pointer is completely leaked once EvenOrOdd has returned.
Last edited on
ah, I was looking at newp ... I see it.
You could return size in a reference parameter. Also, EvenOrOdd is a bad name for a function that returns only the even numbers:

int *even(int *arr, int inSize, int &outSize);
Topic archived. No new replies allowed.