繁体   English   中英

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

[英]Typedef struct pointers correctly pointing to typedef struct (C)

我正在尝试在全局ptr中保存一个malloc的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

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

正如melpomene正确指出的那样,您是在分配指向上下文的指针(称为线程),而不是上下文本身。

然后,在这两种功能中,您都在打印那些指针的存储地址(而不是指针本身)。 因此,对于静态对象(headThread),它们是相同的;对于自动对象(newThread,它每次都在堆栈上分配),它们是不同的。 这里似乎是什么问题?

在两个函数start()和create()中,您要打印以下地址:

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

但是变量newThread是在两个函数中的每个局部(在堆栈中)声明的。

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

要获取已分配的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM