c - Typedef 结构指针正确指向 typedef 结构 (C)

标签 c multithreading pointers struct

我正在尝试将 malloc'd ptr 保存在全局 ptr 中,以便我可以在另一个函数中使用它。理想情况下,我希望在全局范围内有一个更智能的数据结构,但现在我只是想让全局 ptr 工作。

在我的 lwp.h 文件中,我有以下定义:

typedef struct threadinfo_st *thread;
typedef struct threadinfo_st {
   tid_t         foo1
   unsigned long foo2
   size_t        foo3
   rfile         foo4
   thread        foo5
   thread        foo6
   thread        foo7
   thread        foo8
} context;

使用这个线程结构,我的 lwp.c 文件中有两个函数。在第一个函数中,我构造了一个 malloc 线程,然后将数据复制到全局 ptr。然后在第二个函数中,我尝试取消引用全局 ptr 以接收最初创建的线程。为了确认我是否正确执行此操作,我在每一步打印出 ptr 地址。不幸的是,我似乎无法恢复我的原始地址,因此第二个函数中的所有数据都被转移

static thread headThread = NULL;

void create(){
    thread newThread = (thread) malloc( sizeof(thread));
    assert(newThread != NULL)
    // Assign junk to newThread
    printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
    headThread = newThread;
}

void start(){
    thread newThread = headThread;
    printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
}

在主打印中调用 create() 然后 start() :

 newThread is at: 0x7ffdf085c5e0, headThread is at: 0x601890
 newThread is at: 0x7ffdf085c5d8, headThread is at: 0x601890

导致start()函数的newThread中的所有数据都被转移。

我还尝试了以下方法:

static thread *headThread = NULL;

void create(){
    thread newThread = (thread) malloc( sizeof(thread));
    assert(newThread != NULL)
    // Assign junk to newThread
    printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
    headThread = &newThread;
}

void start(){
    thread newThread = headThread;
    printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
}

打印出:

newThread is at: 0x7ffff6294130, headThread is at: 0x601890
newThread is at: 0x7ffff6294128, headThread is at: 0x601890

有谁知道我在这种情况下到底做错了什么? 感谢您的帮助!

最佳答案

int 这两个函数 start() 和 create() 您正在打印的地址:

全局变量 headThread 为 &headThread=0x601890 并保持不变,因为它每次都相同(全局)

但是变量 newThread 是在两个函数的本地(在堆栈中)声明的。

start()中的newThread与create()中的newThread不同,它们在内存(堆栈)中的地址不同,0x7ffff6294130不是0x7ffff6294128。

要获取 malloced ptr,请执行以下操作:

printf("newThread is at: %p, headThread is at: %p\n", newThread, headThread);

那么这是正确的:

static thread headThread = NULL;

不是这个:

static thread *headThread = NULL;

最终将 malloc 更正为:

thread newThread = malloc( sizeof(threadinfo_st)); //better use calloc

关于c - Typedef 结构指针正确指向 typedef 结构 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192742/

相关文章:

c++ - 如何在 C 库的实现文件中使用 C++ STL 容器?

c - 使用位值进行 Base3 编码

c库函数获取事件线程数

c++ - 通过指针将结构传递给函数

c++ - 传递可选对象而不复制它

c - mmap 与 mmap64 有什么区别吗?

c - 为什么 sizeof ('a' ) 在 C 中是 4?

ios - 如何从线程更新 UI

c++ - 将节点数组(可变长度)转换为 const float** 以调用 opencv.calcHist

c - 如何将指向结构的指针设置为 NULL