c++ arry question

just wondering why does this not work ?

I want to figure out the size of an array of a strut but it just returns 0
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
#include "stdafx.h"

struct OBJECT
{
    float X, Y, Z;
};

int blabla(OBJECT test[]);

OBJECT test[230];

int _tmain(int argc, _TCHAR* argv[])
{
	int g = blabla(test);

	return 0;
}

int blabla(OBJECT test[])
{
	int one = sizeof(test);

	int two = sizeof(test[0]);

	int leng = one / two;

	return leng;
}


but when I do it like this it works just fine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"

struct OBJECT
{
    float X, Y, Z;
};

OBJECT test[230];

int _tmain(int argc, _TCHAR* argv[])
{
	int one = sizeof(test);

	int two = sizeof(test[0]);

	int leng = one / two;

	return 0;
}

In example 2, at line 12 the compiler knows that test is of type OBJECT[230] -- that is, it knows how many elements
there are in the array.

In example 1, line 21 is trying to take the size of its parameter. Its parameter is OBJECT[] -- that is, the size is unknown.
(In fact, the size it returns will be sizeof( OBJECT* ), which will be 4 for a 32-bit platform).

hmm that makes sense. any idea on how i can fix this ?
Declare the OBJECT test[] within the _tmain() function of the first example instead of a global variable. Declare the function blabla like this:

int blabla(OBJECT);

This way blabla knows that it is getting an OBJECT passed to it but you don't have to declare it's name.
You have to make the size known or else pass in the number of elements to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// But now blabla can only take an array of exactly 230 elements.
int blabla( OBJECT test[ 230 ] ) {
    // ...
}

// or
int blabla( OBJECT test[], int numElements ) {
}

// or
template< size_t N >
int blabla( OBJECT test[ N ] )
{
    // This function can only be called with fixed length arrays of any size.
}
Topic archived. No new replies allowed.