-
Dynamic array problem
Here is my code: The first, is the structure i use:
Code:
typedef struct _SFont
{
ID3DXFont *Fontobj;
char *name;
LOGFONT FontParams;
}SFont;
Then, i make a variable of that type, which i want it as an array later. I also have a counter.
Code:
unsigned int counter;
SFont *eFont;
char test[30];
Then, I have a function that increases the counter by one:
I change the array size like that and attach a name to the current:
Code:
rFont = (SFont*)realloc(rFont, sizeof(SFont)*counter);
sprintf (test, "ArrayItem %i", counter);
rFont[counter].name = test;
somewhy, this code doesnt work, but crashes. Is there another way i could use dynamic arrays?
-
There is pointers in your struct, realloc sometimes copy your struct bitwisely, this can make your program crash.
Do not use realloc/malloc/free in C++, you should use new/delete.
In this case, you can use STL array. It's name is vector.
-
How would I use new to resize the array?
for example:
r = new int[count]; ??
-
Use array like this:
Code:
#include <vector>
using namespace std;
typedef vector<SFont> vec_font;
vec_font rFont(nSize);
...
// use rFont just like an array
rFont[i] = k;
...
// when you want add item to rFont
rFont.resize(nSizeYouPrefer);
...
-
if you don't have or don't want to use STL do this:
Code:
int size, i;
cout << "how big an array to do want";
cin >> size;
int * array = new int[size];
for(i = 0; i < size; i++)
{
cout << ''enter value for element " << i << endl;
cin >> array[i];
}
//to resize array:
//first declare temp array of same size as original
int * temp = new int[size];
//then copy all of original into temp
for(i = 0; i < size; i++)
{
temp[i] = array[i];
}
//now get new size
int newsize;
cout << "enter new size for array";
cin >> newsize;
//delete memory originally reserved for array
delete [] array;
//declare new memory for array
array = new int[newsize];
//copy temp back into array
for(i = 0; i < size; i++)
{
array[i] = temp[i];
}
//now delete memory reserved for temp
delete [] temp;
//assign NULL to temp
temp = NULL;
Now can add more values (as many as the difference between size and newsize) to array. Most of this is done for you when you use an STL vector.