问题描述
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 **
只是一个指针的指针。那么,一个指令*
包含一个指令的地址
结构,一个指令**
包含一个指令*
包含一个指令的地址的地址
对象。
A **
is just a pointer to a pointer. So where an instruction*
contains the address of an instruction
struct, an instruction**
contains the address of an instruction*
that contains the address of an instruction
object.
要访问指令
指向指针由指令指向**
,你只使用两个星号而不是之一,如(** p).repetitions
或类似的东西。
To access the instruction
pointed to by the pointer pointed to by an instruction**
, you just use two asterisks instead of one, like (**p).repetitions
or something similar.
您可以想像它是这样的:
You can visualize it like this:
instruction* ----> instruction
instruction** ----> instruction* ----> instruction
但是请记住,简单地宣告结构指令**指示;
实际上并没有创建一个指令
结构。它只是创建了持有垃圾的价值的指针。你必须初始化:
Remember, however, that simply declaring struct instruction** instructions;
doesn't actually create an instruction
struct. It just creates a pointer that holds a garbage value. You'll have to initialize it:
struct instruction inst;
// set members of inst...
*instructions = &inst;
...
(*instructions)->repetitions++; // or whatever
不过,它看起来像您使用的是指令**
来指向指令的数组*
秒。要初始化数组,你需要一个为
循环:
However, it looks like you're using an instruction**
to point to an array of instruction*
s. To initialize the array, you need a for
loop:
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);
然后你就可以访问诸如指令的元素[I] - 方式&gt;数据成员
这篇关于C双键指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!