RE: [Dev-C++] dynamic allocation and structs
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <no...@ho...> - 2002-10-25 02:26:11
|
> -----Original Message-----
> From: Per Westermark [mailto:pw...@ia...]
> Sent: Friday, October 25, 2002 1:02 AM
> To: Ioannis Vranos
> Cc: dev...@li...
> Subject: RE: [Dev-C++] dynamic allocation and structs
>
>
> Well Ioannis, I did manage to get a star on the wrong side of
> the struct
> type name, see inserted correction below, so the example was slightly
> broken. However, the example was not a total goose chase try at a
> two-dimensional matrix of entries, but an example of creating a
> one-dimensional matrix (a vector) of pointers to single
> entries, which was
> exactly what the heading suggested "array of pointers to
> entries".
Lets avoid using the term "vector". Well an array of single pointers is
a 2 dimensional array of elements so it is the same.
> If the
> code wasn't obvious, a hint to that fact should have been that I only
> used a single for loop to assign values to the entries.
Which i think doesn't work.
>
> One reason to use alternative two, a vector of pointers to elements
> instead of a vector of elements, is that sorting of the vector only
> require changing the place of the pointers, instead of
> copying the full
> structures.
So you wanted to create a single-dimentional array of elements? Then a
single * would be enough.
>
> Another reason is that it might be used to create a sparse
> matrix, where
> the vector might be very long, but only some index values of
> the vector
> will have an allocated entry.
>
> A third reason is that a vector of pointers might be to store
> different
> types of structs in the same vector, as in:
>
> enum {
> CIRCLE,
> LINE,
> BOX
> };
>
> struct Circle {
> int type;
> int x,y;
> int radius;
> };
>
> struct Line {
> int type;
> int x1,y1,x2,y2;
> }
>
> struct Box {
> int type;
> int x1,y1,x2,y2;
> };
>
> void fill_array() {
> Circle *pCircle;
> Line *pLine;
> Box *pBox;
> int item_count,i;
>
> item_count = 0;
> pCircle = (Circle*)malloc(sizeof(Circle));
> pCircle->type = CIRCLE;
> pCircle->x = 10;
> pCircle->y = 20;
> pCircle->radius = 5;
> myarray[item_count++] = pCircle;
>
> pBox = (Box*)malloc(sizeof(Box));
> pBox->type = BOX;
> pBox->x1 = 15;
> pBox->y1 = 2;
> pBox->x2 = 18;
> pBox->y2 = 5;
> myarray[item_count++] = pBox;
>
> ...
>
> // Draw items.
> for (i = 0; i < item_count; i++) {
> if (myarray[i]) {
> switch (myarray[i]->type) {
> case CIRCLE:
> pCircle = (Circle*)myarray[i];
> // Draw circle
> break;
> case BOX:
> pBox = (Box*)myarray[i];
> // Draw box
> break;
> case LINE:
> pLine = (Line*)myarray[i];
> // Draw line
> break;
> default:
> // Complain about unsupported object type.
> }
> }
> }
I did not get your meaning. Where is myarray definition. I assume
myarray is a single arrray of void *. And?
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.freeurl.com
* Alternative URL: http://run.to/noicys
|