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**
指向的指针指向,您只需使用两个星号而不是一个星号,例如 (**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*
的数组秒。要初始化数组,您需要一个 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
这样的元素.
关于C双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814646/