C 结构指针

标签 c pointers struct

给定的默认结构:

struct counter {
  long long counter;
};    

struct instruction {
  struct counter *counter;
  int repetitions;
  void(*work_fn)(long long*);
};

static void increment(long long *n){
  n++;
}

我的台词:

n = 2;
struct counter *ctest = NULL;

int i;
if( ctest = malloc(sizeof(struct counter)*n){
  for( i=0; i<n ;i++){
    ctest[i].counter = i;
  } 

  for( i=0; i<n ;i++){
    printf("%lld\n", ctest[i].counter);
  }
}

struct instruction itest;

itest.repetitions = 10;
itest.counter = ctest; //1. This actually points itest.counter to ctest[0] right?
                       //2. How do I actually assign a function?    

printf("%d\n", itest.repetitions);
printf("%lld\n", itest.counter.counter); // 3. How do I print the counter of ctest using itest's pointer?

所以我正在努力让这三件事发挥作用。

谢谢

最佳答案

itest.counter = ctest; // This actually points itest.counter to ctest[0] right?

没错。 itest.counter == &ctest[0]。此外,itest.counter[0] 直接引用第一个 ctest 对象,itest.counter[1] 引用第二个,依此类推。

How do I actually assign a function?

itest.work_fn = increment;

How do I print the counter of ctest using itest's pointer?

printf("%lld\n", itest.counter->counter); // useful if itest.counter refers to only one item
printf("%lld\n", itest.counter[0].counter); // useful if itest.counter refers to an array

关于C 结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5807276/

相关文章:

c - 在 C 中循环 stdin

c++ - 将二维数组指针参数分配给局部数组指针变量

c - 在小结构的末尾而不是在 2 个成员之间进行对齐填充是否对性能更好?

c - 使用数组指针对结构进行排序不起作用

iphone - 从 NSMutableArray 添加和提取结构

c - 如何在linux中使用execv系统调用?

c - 在C中寻找垃圾收集的根源

c - 如何在不编写完整解析器的情况下将部分源程序转换为库调用?

c++ - 字符串、 union 和指针

c++ - 有指针的计算机实验室