簡體   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