C双指针

时间:2011-04-28 06:40:46

标签: 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; 

这实际上是如何运作的?我遇到了**指针

的问题

3 个答案:

答案 0 :(得分:10)

**只是指向指针的指针。因此,instruction*包含instruction结构的地址时,instruction**包含instruction*的地址,其中包含instruction对象的地址。< / p>

要访问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等元素。

答案 1 :(得分:1)

  

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));

你得到了struct instruction的5个指针。像这样使用它:

instructions[0]->repetitions = 0;

答案 2 :(得分:0)

instructions是指向struct instruction的指针。

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