指向包含结构体的结构体的指针

发布于 2024-11-05 05:57:25 字数 267 浏览 1 评论 0原文

我正在编写一个多线程应用程序,并且想传递指向结构的指针。

结构中的结构是否需要进行 malloc,或者如果外部结构进行 malloc,是否会防止内部结构在传递指针时被删除或丢失?

我要问的结构是

struct thread_data
{
    position starttile;
    position destinationtile;
    char *message;
};

位置是一个不包含指针的结构本身

I am writing a multithreaded application and would like to pass around pointers to a struct.

Do the structs in the struct need to be malloced or if the outer struct is malloced will it prevent the internal structs from being deleted or lost when passing around the pointer?

Struct I am asking about is

struct thread_data
{
    position starttile;
    position destinationtile;
    char *message;
};

where position is a struct itself that contains no pointers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫性小仙女 2024-11-12 05:57:26

如果结构体包含子结构体,那么它通常都是一块内存。因此不会有单独的分配。

如果该结构包含指向结构的指针,那么我之前的评论将不适用。在这种情况下,这取决于您在做什么。

您是否考虑过发布一小段代码,以便人们知道您的想法。

If the struct contains child structs, then it is generally all one block of memory. And so there would be no separate allocation.

If the struct instead contains pointers to structs, then my previous comment would not apply. In this case, it kind of depends on what you are doing.

Had you considered posting a tiny bit of code so people would have a clue what you had in mind.

明月松间行 2024-11-12 05:57:26

做,您可能会发现管理内存更容易

struct X {
   struct Y data;
};
struct X* var = malloc(sizeof(struct X));

如果您这样

struct X {
   struct Y* pData;
};
struct X* var = malloc(sizeof(struct X));
var->pData = malloc(sizeof(struct Y));

You will probably find it easier to manage memory if you do

struct X {
   struct Y data;
};
struct X* var = malloc(sizeof(struct X));

instead of

struct X {
   struct Y* pData;
};
struct X* var = malloc(sizeof(struct X));
var->pData = malloc(sizeof(struct Y));
望喜 2024-11-12 05:57:26

如果您的外部struct包含实际结构,则无需单独分配它们。
如果您的外部struct包含指向结构的指针,那么它们需要被分配到某个地方。

如果您的外部结构包含实际结构,那就更容易了。即便如此,对于指针,只需确保在内部结构完全分配之前,永远不要将指向外部结构的指针提供给其他线程 - 这可以避免分配时的线程问题。重新分配需要适当的照顾以确保独占访问权。

If your outer struct contains actual structures, there's no need to allocate them separately.
If your outer struct contains pointers to structures, then they'll need to be allocated somewhere.

It is easier if your outer structure contains actual structures. Even so, with pointers, simply make sure that you never make the pointer to the outer structure available to other threads until the inner structures are fully allocated - which avoids threading issues on allocation. Deallocation will require suitable care to ensure exclusive access.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文