c - C中通过指向指针的指针从结构体中获取值

标签 c pointers

我正在用 C 编写一个程序。基本上我有一个包含一些字段和一个指针数组的结构。每个结构体都有一个指针数组,指向另一个结构体,在它们之间形成“连接”。我试图获取存储在指向它的指针的内存地址中的字段的值。

假设是这样。我的内存中有两个这样的节点。 A 和 B。A 在 A 的数组中有一个指针,该指针是对 B 的引用。要获取此指针,我必须执行以下操作:

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

这将获取指针地址*ptr并将其提供给*temp_ptr

现在我想知道的是这个。我怎样才能做到这一点?当我尝试这个时,我得到“表达式必须具有结构或 union 类型”

当我在 Java 中尝试时,我可以做到这一点

int variable = field[0].fieldIWantToGet

我会得到想要的结果。

这是一张图片来阐明我想要实现的预期行为。 Link to behavior

其中结构 A 位于结构的“全局”集合中,并且具有指向其他结构(例如 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;

关于c - C中通过指向指针的指针从结构体中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855102/

相关文章:

C: 如何用 makefile 编译包含在另一个头文件中的头文件?

c++ - OpenCV 免费(): invalid pointer:

c - 指向结构的指针的动态数组 - 如何传递给函数?

c - 在函数内部使用 realloc 扩展数组 - 指针?

c - C 语言的 Opencv 库。这条指令到底是做什么的 int=pointer==0; ?

c - C分配二维整数数组

c - 为什么我不能使用指针加法而不是 malloc

澄清c中回调和函数指针的概念

c++ - 在记录错误时取消引用 ptr 是错误的设计吗?

c++ - 在 C++ 中,指针是否类似于 Excel 工作表中的单元格引用?