给定的默认结构:
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/