簡體   English   中英

通過C中的指針從結構體獲取值

[英]Getting value from struct by pointer to pointer in C

我正在用C編寫程序。基本上,我有一個包含一些字段和一個指針數組的結構。 每個結構都有一個指向另一個結構的指針數組,該另一個結構在它們之間形成“連接”。 我試圖獲取存儲在指向它的指針的內存地址中的字段的值。

假設這個。 我在內存中有兩個這樣的節點。 A和B。A在A的數組中有一個指針,該指針是對B的引用。要獲取此指針,我必須執行以下操作:

*temp_ptr = (*ptr).pointer_array[0]

這將獲得指針地址*ptr並將其提供給*temp_ptr

現在我想知道的是。 我怎樣才能做到這一點? 嘗試此操作時,出現“表達式必須具有結構或聯合類型”

當我嘗試使用Java時,我可以這樣做

int variable = field[0].fieldIWantToGet

我會得到理想的結果。

這是一張圖片,用於闡明我要嘗試獲得的預期行為。 鏈接到行為

Struct A在“全局”結構集合中,並且具有一個指向其他Struct的指針數組,例如B

這是我項目中的一些代碼。

#define GLOBAL_PTR_ARRAY_SIZE 10

Node* global_node_array[10];  

typedef struct Node{

unsigned char node_id;
int *ptr_array[10];
int ptr_array_size;


}Node;



void append_connection(short position, short destination) {   

    Node* position_ptr = global_node_array[position];        
    Node* destination_ptr = global_node_array[destination];

    if ((*position_ptr).ptr_array_size < GLOBAL_PTR_ARRAY_SIZE) {   
        int current_ptr_array_size = (*position_ptr).ptr_array_size;  

        (*position_ptr).ptr_array[current_ptr_array_size] = destination_ptr;

        (*position_ptr).ptr_array_size++;

}

void print_id(Node* ptr) {

    node* dptr = NULL;

    dptr = ptr->ptr_array[0];

    pptr = (int) (*ptr).ptr_array[0];

    fprintf(stdout, "%d connection to %d exists", (*ptr).node_id, dptr- 
   >node_id);      
}


int main(int argc, char const *argv[])
{
append_connection(0,1);
print_id(global_node_array[0]);

return 0;
}

您的圖片顯示的是結構數組,而不是指針。 但是下面的示例涵蓋了兩者。

struct a{
    int field1,field2;
}

struct b{
    struct a m[10];
}

struct c{
    struct a *m[10] 
}




   /* and usage */        
    struct c *x;
    struct b *y;

    x -> m[5].field1;
    y -> m[5] -> fileld1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM