#### Archived

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

# C++ Question: How to retrieve the number of elements of an array of dynamic objects

This topic is 5525 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

In Java, this is simply done by using arrayname.size() or so, right? The method I use in C++ is sizeof(arrayname)/sizeof(datatype) where datatype is int. Well, the problem with this method is that it''s not flexible. The sizes of datatypes are defined by the compiler and so differ from system to system (or is it the OS?), right? On my system, running Win98, sizeof(int) is 4. If I compile the ocde on another system, I guess things may go wrong. So my question is, is there any other method (which definitely has to be flexible) to get the number of elements of an array of dynamic objects? NOTE: The size of the array is not predetermined; like an array of values to be loaded from a file (sorta).

##### Share on other sites
well, when I want to count the number of chars in a string, I do a simple while(1) loop until an element returns a NULL. This may or may not work for you, since you may want them to be NULL or whatever. There are so many strange things you can do in programming. This works for me though. Hope it helps.

"What is darkness? It doesn''t exist where there''s light, and without light, it''s nothing..."

##### Share on other sites
If the array has been allocated with new, malloc or anything like that ... you don''t really have an array, but a pointer to dynamically allocated data. In which case, recovering the size is strictly impossible. sizeof(pointer) is constant regardless of the number of elements (though the exact size is platform-specific).

HOWEVER, if you''re using a C++ std::vector (standard dynamic array class), then its size is (surprise !) arrayname.size(). std::vector is probably closest to Java arrays ... except they are type-checked (e.g. std::vector<int>).

Note - C99 adds dynamic arrays and fixed-size types (int32_t ...) but that''s probably irrelevant here.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

##### Share on other sites
If you overload operator new, you can do it like this:

  void* operator new(int nSize){int* pRet;      pRet = (int*)malloc(nSize+sizeof(int));   *pRet = nSize;   return pRet+1;}int GetArrayLen(void* pArray){   return ((int*)pArray)[-1];}

i''m staggered

##### Share on other sites
quote:
Original post by Evil Bill

If you overload operator new, it has to be for the serious intent of providing some custom memory allocation schema, not for whimsical fancies such as finding out the length of an array. Abusing a facility in such a manner creates more problems than it solves, which you''ve nicely illustrated for us by overloading the wrong operator, and failing to take account of alignment.

We already have std::vector, which is the modern-day antidote to the "well, it seemed a good idea in the 70''s" C-style array.

##### Share on other sites
True, i forgot about alignment, and yes, it does usually cause more problems than it solves. What do you mean i overloaded the wrong operator? I don''t understand ...

##### Share on other sites
quote:
Original post by Evil Bill
What do you mean i overloaded the wrong operator? I don''t understand

Big hint: you don''t use operator new to allocate arrays.

##### Share on other sites

Gobsmacked me''self - now I''ve split me lip

Use a std:vector for little things that don''t get moved around much and a std:list for whopping great mother-arrays that get chopped and changed a lot. Hell use a dequeue if you want to pop things on\off fronts and backs.

Use STL - you know it makes sense (else you might have to return the size of your object in the first 4 bytes of your array by hacking operator NEW or something equally NASTY like that!).

##### Share on other sites
SabreMan: Doh! I'm having a bad day (thats my excuse anyway)

Edit: Well, it should work. If you only want one object. And if you don't want it aligned. Oh, and you don't delete it either... But apart from that, it'll tell you the size of the object (not that its incredibly useful)

[edited by - Evil Bill on December 3, 2002 12:10:25 PM]

##### Share on other sites
quote:
Original post by Evil Bill
Edit: Well, it should work. If you only want one object. And if you don''t want it aligned. Oh, and you don''t delete it either... But apart from that, it''ll tell you the size of the object (not that its incredibly useful)

Please just quit while you''re... er, behind!

##### Share on other sites
The easiest solution to your problem is to keep track of the size of the array. Have an integer index variable that you increment when you add an element to the array, and decrement when you delete an element of the array. As long as you keep these two things synchronized you''ll be able to determine the size of the array at any point in your program.

##### Share on other sites
quote:
Original post by Anonymous Poster
The easiest solution to your problem is to keep track of the size of the array.

No it is not.
quote:

Have an integer index variable that you increment when you add an element to the array, and decrement when you delete an element of the array.

This is what vector already does for you. The easiest solution is to use that rather than load yourself with additional responsibilities.
quote:

As long as you keep these two things synchronized

And therein lies a problem.

##### Share on other sites
Saber,

You are correct, this is exactly what vector does for you. But you know what? Not everyone want''s to use STL''s vectors.

It irritates the hell out of me when I see people ask questions and never have the questions get answered they are only told to look else where. There are plenty of times that STL will not be available to you for use. It might be an engine constraint, a console constraint, or maybe your not even using C++. So it is a good idea to know how to solve this problem when you are not able to use STL.

So let me restate, If you want to determine the size of a dynamic array with sizeof it is impossible. The correct way to keep determine the size of an array like this is to have an integer value that you increment/decrement when you allocate/deallocate items to the array. You must keep this value synchronized with the array which isn''t that considering the value will be used again to allocate another item onto the array.

This is the correct solution to the problem. However if you are using C++ and can use the STL, then you should look into the templated vector class. This is basically STL''s implementation of an array class that keeps track of the size of the array, as well as many other things.

##### Share on other sites
quote:
Original post by Anonymous Poster
You are correct, this is exactly what vector does for you. But you know what? Not everyone want''s to use STL''s vectors.

Deciding that you don''t want to use the right tool for the job is pig-headed.
quote:

It irritates the hell out of me when I see people ask questions and never have the questions get answered they are only told to look else where.

And it irritates the hell out of me when I see people who continually insist of making life more difficult for themselves and other people than it need be.
quote:

There are plenty of times that STL will not be available to you for use.

Until that is demonstrated to be the case, I shall assume std::vector is available. After all, we are talking C++ and std::vector is mandated.
quote:

It might be an engine constraint, a console constraint, or maybe your not even using C++.

Now you''re just being silly. The OP specifically asked about C++. If he wasn''t using C++, I''d hardly be recommending a C++ solution. He also stated he was using Win98.
quote:

So it is a good idea to know how to solve this problem when you are not able to use STL.

Maybe, but that''s not what''s being asked.
quote:

So let me restate, If you want to determine the size of a dynamic array with sizeof it is impossible.

Correct.
quote:

The correct way to keep determine the size of an array like this is to have an integer value that you increment/decrement when you allocate/deallocate items to the array.

Only if your definition of correctness involves creating more work for yourself than is necessary. You are intentionally creating confusion for the OP because of some silly preconception of your own.

##### Share on other sites
ok, that bein the case, can the operator new be used with std::vector blah blah blah. I don''t think that''s really C++ like, is it?

##### Share on other sites
Well this is pretty amusing.

Thoughts:

A) Not everyone who uses C++ knows how to use Templates. And even if they do know how to use templates the STL implementations of many things are very confusing.

B) Using the right tool for the job intails determening what the job is, and who is doing the job. In this case I''d suspect that the origional poster isn''t fluent in C++, he apparently knows java. But the likely hood that he knows how to understand and use templates is very small. So although it''s good to point out that you can do the same thing with "STL::vector", it would be good to also point out how to do this without the need for vectors.

C) Finally I''d suggest the people visiting this thread take a breath of fresh air and chill out! Some how the point of this thread went from "Help out" to "I''m right and your not". That''s pretty pathetic. If you''ve got something useful to add to the thread your more than welcome but if all your going to do is rip appart other peoples suggestions then you aren''t doing anything but proving how juvenile you are.

##### Share on other sites
quote:
Original post by liquidAir
ok, that bein the case, can the operator new be used with std::vector blah blah blah. I don't think that's really C++ like, is it?

The point is, you don't need to use "new" to allocate data with vector - it already does it all for you behind the scenes. You can stop thinking about all sorts of manual housekeeping tasks and just get on with whatever you are doing. Here's a sample use:

    #include <vector>#include <cassert>using std::vector;int main(){  vector<int> v;  // a vector containing ints  // add a few ints...  v.push_back(1);  v.push_back(2);  v.push_back(3);  int i = v[1];  // retrieve the 2nd element  assert(i==2);  // what's the size?  int len = v.size();  assert(len==3);}

A C++ std::vector is very like the Java arrays you are already used to.

[edited by - SabreMan on December 3, 2002 2:22:38 PM]

##### Share on other sites
quote:
Original post by Anonymous Poster
Well this is pretty amusing.

quote:

A) Not everyone who uses C++ knows how to use Templates.

That is no excuse not to learn how to do something. Particularly for the piffling amount of effort it takes to learn how to be a consumer of ready-written templates.
quote:

And even if they do know how to use templates the STL implementations of many things are very confusing.

That''s a complete non-argument. Quite clearly, the OP is already finding it confusing to get the length of an array.
quote:

B) Using the right tool for the job intails determening what the job is, and who is doing the job.

The job is twofold: "using an array" and "being able to get the length of an array". A C array is subject to all manner of bogosity that will cause the OP to have to learn about all those bogosities as he goes. One such bogosity is that you cannot get the length. There are others.
quote:

In this case I''d suspect that the origional poster isn''t fluent in C++, he apparently knows java.

Then he will find std::vector to be closer to the concept of a Java array than the brain-damaged crap that is a C-style array.
quote:

But the likely hood that he knows how to understand and use templates is very small.

As is the likelihood he knows how to understand and use C arrays. However, templated classes such as std::vector behave in a sensible manner and are for more useful to learn how to use.
quote:

So although it''s good to point out that you can do the same thing with "STL::vector", it would be good to also point out how to do this without the need for vectors.

When that need arises. Which it apparently hasn''t.
quote:

C) Finally I''d suggest the people visiting this thread take a breath of fresh air and chill out! Some how the point of this thread went from "Help out" to "I''m right and your not".

The reason for that is that you presented bad advice which will make the OP''s C++ exploits that bit more difficult.
quote:

That''s pretty pathetic.

Then stop doing it.
quote:

If you''ve got something useful to add to the thread your more than welcome but if all your going to do is rip appart other peoples suggestions then you aren''t doing anything but proving how juvenile you are.

On the contrary, I''ve enough experience of building massive C++ (and other) applications that I''m fully aware of what sorts of problems C arrays present. I''m offering the full weight of that experience to present a solution above and beyond what the OP asked for.

##### Share on other sites
I hate to burst your bubble there saber, but that last annon poster was different than the previous ones.

##### Share on other sites
quote:
Original post by evaclear
I hate to burst your bubble there saber, but that last annon poster was different than the previous ones.

How exactly does that "burst my bubble"?

##### Share on other sites
quote:
Original post by evaclear
I hate to burst your bubble there saber, but that last annon poster was different than the previous ones.

They may have been different but their stances were equally idiotic.

##### Share on other sites
quote:
Original post by liquidAir
Well, the problem with this method is that it's not flexible. The sizes of datatypes are defined by the compiler and so differ from system to system (or is it the OS?), right? On my system, running Win98, sizeof(int) is 4. If I compile the ocde on another system, I guess things may go wrong.

I think there's something wrong with your assumption that it
won't correctly compile on different a system.

But you also said that it should be possible, but you didn't
notice it.

The key phrase is 'compile on another system', if you compile on
another system, you actually give the compiler of the other
system the chance to fill in the correct value. The sizeof()
method is much better than simply using a constant value like 4.
Because you then you would have to edit the code for compiling
it on a platform with sizes different from the sizes of yours.

[edited by - Beast Master on December 3, 2002 8:39:32 PM]

##### Share on other sites
Hi.
Can anyone explain me, why posted code wouldn''t work. I have seen some ''extensions'' of ''new'' operator, some for debugging purposes,so I guess it''s common aproach? I am using std::vector and I am happy with it, but sometimes I just need simple array and then I have to #define something in order to have it''s size.

void* operator new(int nSize){  int* pRet;  pRet = (int*)malloc(nSize+sizeof(int));  *pRet = nSize;   return pRet+1;}int GetArrayLen(void* pArray){   return ((int*)pArray)[-1];}

##### Share on other sites
quote:
Original post by ibolcina
Hi.
Can anyone explain me, why posted code wouldn''t work.

Because operator new[] is used for arrays, not operator new.

For those who believe in God, most of the big questions are answered. But for those of us who can''t readily accept the God formula, the big answers don''t remain stone- written. We adjust to new conditions and discoveries. We are pliable. Love need not be a command or faith a dictum. I am my own God. We are here to unlearn the teachings of the church, state, and our educational system. We are here to drink beer. We are here to kill war. We are here to laugh at the odds and live our lives so well that Death will tremble to take us -- Charles Bukowski