سؤال

I'm trying to load a whole lot of primitives using Direct3D 9, so I need to pass a large array of struct to virtual buffer. But if I do it with malloc(), my sizeof() function returns a wrong value (always 4). And if I typically allocate stack memory (array[number]), stack can overflow because of number of elements. Is there any alternative to it? How do I allocate stack memory that can load as much data?

P.S. I'm not gonna draw them all to the screen, but I still need their vertex information.

هل كانت مفيدة؟

المحلول

When used with a pointer, the sizeof operator returns the size of the pointer and not what it points to.

When you allocate memory dynamically (in C++ use new instead of malloc) you need to keep track of the amount of entries yourself. Or better yet, use e.g. std::vector.

نصائح أخرى

If you called malloc, you called it with the size of the amount of space you wanted. If you want to know later on how big the allocation is, you need to keep that information around yourself.

Since your using C++, you could useIf you called malloc, you called it with the size of the amount of space you wanted. If you want to know later on how big the allocation is, you need to keep that information around yourself.

If that's too much trouble, since your using C++, you could use a <vector> or similar, which will track its own size. a vector or similar, which will track its own size.

Yes with malloc() and then using sizeof() will give you 4. That's the pointer size.

If you are just wondering how to fill your values in ptr then refer code below:

int numOfItems = 10;
int* pArr = (malloc(sizeof(int)*numOfItems);
for (int i=0;i<numOfItems;i++)
    pArr[i] = i+1;

Your best option may be to allocate a std::vector dynamically and using a smart pointer.

std::shared_ptr< std::vector< your data type> > vertices( new std::vector( number );

Now you don't overflow the stack, all relevant housekeeping is done by std::vector and std::shared_ptr, and most importantly memory will get deleted.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top