简体   繁体   English

指向结构的指针

[英]Pointer to Pointer to a Structure

I have following structure that contains two integer values. 我有以下包含两个整数值的结构。

struct data
{
 int v1;
 int v2;
};

/*some functions on struct data*/

struct data* create(int v1,int v2);
void printData(struct data *d);

Now I have the following structure vec wich will kind of act like a list and this structure has size and a pointer to a pointer to a structure of type data. 现在,我具有以下结构,该结构有点像列表,并且该结构具有大小和指向类型数据结构的指针。

struct vec
{
 int size;
 struct data **array;
};

/*possible functions for vec structure*/
struct vec* createVec();
void addFront(struct vec *v, struct data* dta);

Since i am a beginner to pointers i would like to clarify and confirm my understanding. 由于我是指针的初学者,因此我想澄清和确认我的理解。

  1. struct data **array; 结构数据**数组; I am trying to figure out how this is working so i have drawn a visualization of what it might possibly be and would appreciate if someone can confirm if i am correct or not. 我试图弄清楚这是如何工作的,所以我对可能的情况进行了可视化处理,如果有人可以确认我是否正确,我将不胜感激。

指向类型数据结构的指针

I know this is not the greatest data structure etc this is being done strictly to help me clarify my understanding in pointers. 我知道这不是最大的数据结构,因此将严格执行此操作以帮助我阐明对指针的理解。

To help you clarify everything in your mind (and your code), you can do the following: 为了帮助您弄清思路(和代码),可以执行以下操作:

typedef struct data* data_ptr

Then, the struct vec can be written as 然后,struct vec可以写成

struct vec
{
 int size;
 data_ptr *array;
};

So, array is indeed a pointer to a pointer to a data struct. 因此,数组确实是指向数据结构的指针。 Array however is a misleading name, since you could be able to get what you want with other data structures like lists etc. If you decide to stick with the array, then you should allocate memory correctly and free it at the end, and the structure looks like what you have drawn. 但是,数组的名称具有误导性,因为您可以通过列表等其他数据结构获得所需的内容。如果决定坚持使用数组,则应正确分配内存并在最后释放内存,然后结构看起来像你所画的。

Therefore, (after the correct initializations), array[i] will give you a pointer to the i-th data struct, and array[i]->v1 should give you the v1 value of the i-th struct. 因此,(在正确的初始化之后), array[i]将为您提供第i个数据结构的指针,而array[i]->v1应为您提供第i个结构的v1值。

Your visualization is fine. 您的可视化效果很好。

If we look at your diagram, we'd expect vec->array[0] (the first element of your array) to be a pointer to struct data , right? 如果我们看一下您的图,我们期望vec->array[0]vec->array[0]的第一个元素)是指向struct data的指针,对吗?

The array indexing operation ( [0] ) will de-reference the first element, which means stripping a pointer from the type. 数组索引操作( [0] )将取消引用第一个元素,这意味着从类型中删除指针。

So, if the type of array is struct data ** , the type of array[0] will be struct data * (notice one fewer * ), which is what we expect. 因此,如果array的类型是struct data ** ,则array[0]的类型将是struct data * (注意少一个* ),这就是我们所期望的。

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

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