给定的默认结构:
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;//
事实上它指向了
ctest[0]对吧?
正确的。itest.counter == &ctest[0]
另外,itest.counter[0]
直接指第一个ctest对象,itest.counter[1]
指第二个,等等。
如何实际分配函数?
itest.work_fn = increment;
我该怎么办
使用打印ctest计数器
itest的指针?
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 - C结构指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5807276/