开发者

how to create a linked list of tables, a table represents a group of elements

what I am trying to do is represented in my other question with code.

Basically I need to keep in memory a table of elements (structs), there's no fixed number of elements that can exist, but it is small, but I still can't use an array.

And I don't want to use a linked list of elements because I don't want to keep adding and deleting elements everytime I need to change anything.

Instead what I want to do is allocate a chunk of memory with a single malloc, that chunk of memory will be la开发者_如何学Pythonrge enough for say, 100 elements, and if in the rare case that I need more, I can allocate another chunk of 100 elements and link it to the original....

Is this a good idea? is there a name for this kind of structure? it's kinda of like dynamic expanding array? Do people actually use this? or I am just on crack? if this is bad idea, what do you recommend using instead?

Thanks

typedef struct Tb{
   POINT points;
   POINT *next;
} TABLE;

typedef struct Pt{
   int x;
   int y;
}POINT;


POINT *mypoints;
int a = 10;
int b = 1000;

mypoints = (POINT*) malloc (100 * sizeof(POINT));

for (int i =0; i < 100; i++) {
    mypoints->x = a++;
    mypoints->y = b++;
    ++mypoints;
}


Such allocation schemes have been used everywhere from the early Unix file system to Python's internal list allocation.

Code on!


This is a common data structure, that I've seen in some places named as "linked list of tables".

I'm assuming you are looking for a C++ answer since your code is in C++. The C++ standards does not impose a specific data structure for its containers. However, the specification kind of forces the compiler builders to use a specific data structure, since it it is the most appropriate to fulfill the specifications.

In C++, this is the case for the std::deque, which typically uses the data structure you describe above. To quote the documentation on the subject : "As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays". See : https://en.cppreference.com/w/cpp/container/deque

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜