C双指针

标签 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 的地址对象。

访问instructioninstruction** 指向的指针指向,您只需使用两个星号而不是一个星号,例如 (**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/

相关文章:

c - 使用 fscanf 无法按预期读取文件

c - time.h - struct tm 和毫秒

C 文本算法

c - 何时使用 'if' 与 'switch' 语句?

c - 将 f(mystruct *a) 更改为 f(const mystruct *a) 会破坏 C 中的 API/ABI 吗?

c - 替换 HTTP 源中的 HTML 实体

c - 二叉搜索树上的段错误 - 大排序

c++ - 当工件是库且标志影响 C 或 C++ header 时,功能标志/切换

c++ - Xcode需要哪些设置才能构建此代码

c - 在 C 中打印数字的除数