Jump to content
  • Advertisement
Sign in to follow this  
blinky41

size of struct array

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

i have a struct struct myStruct { char name[50]; char type[50]; int32 age; int32 value; int32 chance; }; ... myStruct* myS; ... myS = new myStruct[8]; how would i find the number of entries in the array. I tried: int32 num = sizeof(myS ) / sizeof (myStruct); //112 / 4 int32 num = sizeof(myS ) / sizeof (myS[0] ); //112 / 4 int32 num = sizeof(myS ) / sizeof (*myS ); //112 / 4 it doesnt give me 8 it gives me 28; 112 / 4

Share this post


Link to post
Share on other sites
Advertisement
(1) If it's C++ use a std::vector instead
(2) you're creating the array so just store the size:


myStruct *myS = new myStruct[8];
unsigned int mySCount = 8;



-me

Share this post


Link to post
Share on other sites
One of my first lessons in C was this. The answer I was told was "You created it, so you should know." In other words, it's your responsibility to keep track of it, because technically all your array is, is a spot in memory.

sizeof() doesn't work because that is evaluated at compile time and just ends up as a constant.

Share this post


Link to post
Share on other sites

struct myStruct
{
std::string name;
std::string type;
int32 age;
int32 value;
int32 chance;
};

typedef std::vector< myStruct > MyStructs;

...

MyStructs myS;
myS.resize(8);
myS[1].age = 15;
myS[2].chance = 10;
std::cout << myS.size();



This is C++.

The use sizeof() to determine number of elements of such structures is bad in the first place, but might have place in C. For C++, it's an obsolete concept.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!