C双指针

struct counter{ long long counter; } struct instruction{ struct counter *counter int repetitions; void (*work_fn)(long long *); }; int ncounter; //number of counters struct counter *counter; //counter array int nthreads; //number of threads int *ninstructions; //number of instructions struct instruction **instructions; 

这实际上是如何工作的? 我在使用**指针时遇到问题

A **只是指向指针的指针。 因此,当instruction*包含instruction结构的地址时, instruction**包含instruction*的地址,该instruction包含instruction对象的地址。

要访问由instruction**指向的指针指向的instruction** ,您只需使用两个星号而不是一个星号,如(**p).repetitions或类似的东西。

您可以像这样将其可视化:

 instruction* ----> instruction instruction** ----> instruction* ----> instruction 

但是,请记住,只是声明struct instruction** instructions; 实际上并没有创建instruction结构。 它只是创建一个包含垃圾值的指针。 你必须初始化它:

 struct instruction inst; // set members of inst... *instructions = &inst; ... (*instructions)->repetitions++; // or whatever 

但是,看起来你正在使用instruction**指向一个instruction**数组instruction* 。 要初始化数组,您需要一个for循环:

 instructions = malloc(sizeof(struct instruction*) * num_of_arrays); for (i = 0; i < num_of_arrays; ++i) instructions[i] = malloc(sizeof(struct instruction) * size_of_each_subarray); 

然后你可以访问像instructions[i]->datamember这样的元素。

struct instruction **instructions; // How does this actually works ? I am having trouble with ** pointers

我不确定真正的问题是什么,但我会尝试回答这个问题。

双指针是指向指针的指针。 例如,它可以作为指针数组(如果你相应地分配内存)。 例如:

 instructions = malloc(5*sizeof(struct instruction*)); for (int i = 0; i < 5; i++) instructions[i] = malloc(sizeof(struct instruction)); 

你得到了很好的5个指向struct instruction数组。 像这样用它:

 instructions[0]->repetitions = 0; 

instructions是指向struct instruction的指针。

这意味着*instructions将为您提供指向struct instruction的指针。 这种构造通常用于创建指向某些复合类型的动态指针数组。