• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# C++ Gurus...

## Recommended Posts

I''m trying to find out how many elements are in an array:  int blah[10];  I want to get the number 10 - Derek

##### Share on other sites
You''re out of luck there... you''re supposed to KNOW how many elements are in an array, because you can''t query its size in C++. You can in Java though.

People might not remember what you said, or what you did, but they will always remember how you made them feel.
~ (V)^|) |<é!t|-| ~

##### Share on other sites
sizeof( blah ) returns the number of bytes in the entire array. So, if you divide this by the size of a single element in the array, you''ll get the number of elements in the array.

For example, the program below prints "10"

#include

int main()
{
int blah[ 10 ];
printf( "%d\n", sizeof( blah ) / sizeof( blah[ 0 ] ) );
return 0;
}

##### Share on other sites
quote:
Original post by mother
sizeof( blah ) returns the number of bytes in the entire array.

No it doesn''t, it returns the number of times a char fits into the size of the array, which on most platforms happens to be a byte. This is not guaranteed to be a byte by the C++ standard.

People might not remember what you said, or what you did, but they will always remember how you made them feel.
~ (V)^|) |<é!t|-| ~

##### Share on other sites
Sir, I challenge you to a duel.

From section 5.3.3.1 of the HTML version of the December 1996 Working Paper for the ISO/ANSI C++ Standard (the Nov 97 version became the standard),

"The sizeof operator yields the number of bytes in the object representation of its operand."

and from section 5.3.3.2 of the same,

"This implies that the size of an array of n elements is n times the size of an element."

Also, straight from MSDN for VC++ 6.0,

"The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate
types)."

And from the example on the same page:
size_t sizearr =                       // Count of items in array             sizeof( array ) / sizeof( array[0] );

I also checked the Borland compiler''s help at work. It says bytes, as well.

Mike Roberts
aka milo
mlbobs@telocity.com

##### Share on other sites
Mike:

That works great...in the main loop

#include #include #include void SortArray(int *array){ int temp; for(int j = 0; j < 1000; j++) { for(int i = 0; i < 1000; i++) { if(array > array[i + 1]) { temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; } } }}void FillArray(int *array){ srand((unsigned)time(NULL)); for(int i = 0; i < 1000; i++) array[i] = abs(rand()%100);}int main(){ int blah[1000]; size_t sizearr = sizeof( blah ) / sizeof( blah[0] ); printf("%d", sizearr); FillArray(blah); SortArray(blah); return 0;}

How come if I use the sizeof / sizeof I get a one inside the functions?

- Derek

##### Share on other sites
Actually, chars are always guaranteed to be bytes, as far as I can tell (they''re the only data type with a certain size on all platforms).

But to answer your question about why it doesn''t work elsewhere: you have to understand how the function sees it. It sees a pointer to an integer, which may or may not have integers after it. There''s no way to know at run time nor at compile time (without heavy parsing and restrictions). Pass in the length as another parameter. If this happens in other languages, it''s because they''re doing it this way under the hood (with the minor exception of certain constructs like strings in Pascal, where the length is a part of the dataset).

##### Share on other sites
The sizeof operator has two distinct uses:
sizeof unary-expression
sizeof (type-name)
The result in both cases is an integer constant that gives the size in bytes of how much memory space is used by the operand (determined by its type, with some exceptions). The amount of space that is reserved for each type depends on the machine.
In the first use, the type of the operand expression is determined without evaluating the expression (and therefore without side effects). When the operand is of type char (signed or unsigned), sizeof gives the result 1. When the operand is a non-parameter of array type, the result is the total number of bytes in the array (in other words, an array name is not converted to a pointer type). The number of elements in an array equals sizeof array/ sizeof array[0] .

If the operand is a parameter declared as array type or function type, sizeof gives the size of the pointer. When applied to structures and unions, sizeof gives the total number of bytes, including any padding.
You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with an lvalue that designates a bit field object.
The integer type of the result of sizeof is size_t, defined in stddef.h.

You can use sizeof in preprocessor directives; this is specific to Borland C++.
In C++, sizeof(classtype), where classtype is derived from some base class, returns the size of the object (remember, this includes the size of the base class).

Borland C++ 5.0 Programmer''s Guide

 Null and Void"In this house we obey the laws of thermodynamics!" --Homer Simpson

##### Share on other sites
You can find out how many elements are in an array very easily. Heres how.

Lets say you have an array called values. This line of code will tell how many elements are in that array.

int number = sizeof( values ) / sizeof( values[0] );

I hope this helps.

-Snyper

##### Share on other sites
Snyper, as discussed above, this will not work if you do not have the variable declared in the scope in which your sizeof expression appears.

##### Share on other sites
Bjarne Stroustrup, the C++ Programming Language:
quote:

Sizes of C++ objects are expressed in terms of multiples of the size of a char, so by definition the size of a char is 1. The size of an object or type can be obtained using the sizeof operator. This is what is guaranteed about sizes of fundamental types:

1 == sizeof( char ) <= sizeof( short ) <= sizeof( int ) <= sizeof( long )

[ snip ]

In addition, it is guaranteed that a char has at least 8 bits.

Note the "at least" in there. There is no guarantee for the 8 bits, it could be 16, depending on the system size of a char.

People might not remember what you said, or what you did, but they will always remember how you made them feel.
~ (V)^|) |<é!t|-| ~

Edited by - MadKeithV on October 4, 2000 5:07:01 AM

##### Share on other sites
Die Unicode ! Die ! ;-)))) Don''t we all hate it ?

##### Share on other sites
I''m sure the Japanese and Chinese don''t hate it!

People might not remember what you said, or what you did, but they will always remember how you made them feel.
~ (V)^|) |<é!t|-| ~

##### Share on other sites
Want a real dumb a weird way to do it....

pass through the array with na infinite loop, take out the value at the array every time (and add some counter, obviosly) AND**** when you get an error you''ll know your reached the end... So youd have to catch this error (methinks)...

WOOOOOOOppss, I forgot, what happens if at the end of the array you have another piece of data, which doesn''t throw any kind of error... weeeellll back to the drawing board for another wierd and dumb idea....

##### Share on other sites
make a array class

class myIntArray{  public:    myIntArray(int size):s(size), a(new int[size]){}    ~myIntArray()    {      delete [] a;    }    size(); // more functions like this - add(int) and stuff   private:    int s;    int * a;}[\code]

##### Share on other sites
make a template class and use operator overloding instead...
note tho that anyway you do it youll get an performance hit.

##### Share on other sites
quote:
Bjarne Stroustrup, the C++ Programming Language:

Sizes of C++ objects are expressed in terms of multiples of the size of a char, so by definition the size of a char is 1. The size of an object or type can be obtained using the sizeof operator. This is what is guaranteed about sizes of fundamental types:

1 == sizeof( char ) <= sizeof( short ) <= sizeof( int ) <= sizeof( long )

In addition, it is guaranteed that a char has at least 8 bits.

Note the "at least" in there. There is no guarantee for the 8 bits, it could be 16, depending on the system size of a char.

That is all well and good, but Mr. Stroustrup is not the final word on C++. The ISO/ANSI board is the final word. And quoting their documents (per my earlier post) (anyone know where the final or most current version of the standards doc is on the web) it says bytes. Would you like to argue that a byte on some systems is not 8 bits.

Also, given Mr Stroustrup's definition, wouldn't the calculation of an array size given by many in this thread still work out correctly in all instances? Can you have a type smaller than a char on a system where char is 16 bits. I don't think sizeof is going to return .5 for such a type. So can it exist?

And while we are on the subject, and I may be wrong here, even though sizeof is an operator, I believe its result is always calculated at compile time and not at run time. Anyone know if I'm right or wrong on that one.

Mike Roberts
aka milo
mlbobs@telocity.com

Edited by - milo on October 4, 2000 5:21:34 PM

Edited by - milo on October 4, 2000 5:24:44 PM

##### Share on other sites
You all just go ahead and discuss... I''m just letting the original poster know the way to work around this.

If you want an array with (for example) the 10 high scores, the define a variable MAX_HIGH_SCORES and use this in the array definition and in your code.

here they are:
// Define max. number of high scores
#define MAX_HIGH_SCORES 10

// Declare variable
int iaHighScores[MAX_HIGH_SCORES];

// Clear array
for( int i = 0; i < MAX_HIGH_SCORES; i++ )
{
iaHighScores = 0;
}

##### Share on other sites
Use STL for arrays. STL rocks.

-Jussi

"All it took was one lonely kiss"

##### Share on other sites

int number = sizeof( values ) / sizeof( values[0] );

It definitely won''t work with dynamically allocated memory. Besides, you always specify the size of an array in code, so it will probably be easier just to look in the code.

Snale
+--Java Game

##### Share on other sites
I had to scroll all the way to the bottom of this page before someone pointed that out, dynamic arrays will bomb, They compile but,
long *SomeArraryPtr = new ElementSize[nVariable];
sizeof(SomeArrayPtr)/sizeof(ElementSize)
reports 0

unless SomeArray is defined with a constant number of elements.
i.e. long SomeArray[20];
then it will work.I''m not sure for
long *SomeArrary = new _somestruct[20];

Why not just use an int, or perhaps this assembler code for the delete function, make statement like
delete [] somearray;
and debug in asm. It finds the number of bytes or whatever to delete, I used visual c++ 6.0 and got the asembler code. To long to post here, but e-mail me JesterSI@metacrawler.com

- Keep it simple stupid

• ### Forum Statistics

• Total Topics
627736
• Total Posts
2978868

• 10
• 10
• 21
• 14
• 12