C结构指针
默认结构:C结构指针
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; //这个 实际上指向itest.counter到 ctest [0]对不对?
没错。 itest.counter == &ctest[0]
。此外,itest.counter[0]
直接指第一CTEST对象,itest.counter[1]
是指第二个,等
实际上,我怎么分配功能?
itest.work_fn = increment;
如何 打印的使用 ITEST的指针CTEST柜台?
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
- 这指向CTEST的ADDRES。 (这是相同的,因为它的第一个元素的ADDRES)
- 你应该申报蒙山相同的签字:一些功能(比如
void f(long long *)
),在这里写itest.work_fn = f;
for(int i = 0; i < n; ++i) printf("%lld\n", itest.counter[i].counter);
static void increment(long long * n){ n ++; } 说如果我想使用这个功能? itest.work_fn =增量//那么n呢?我如何通过它? – Jono 2011-04-27 16:33:30
你可以调用'itest.work_fn(n);'这会增加你的n。 – 2011-04-27 16:48:42
没有。只是'itest.work_fn =增量'。 – 2011-04-27 16:51:17
是它。但也许它是这样更清楚:
iter.counter = &ctest[0];
itest.work_fn = increment;
printf("%lld\n", itest.counter->counter);
这就是如果你打算只有一个计数器。从你的代码中你想要多个,也许你应该在struct指令中存储数字。 如果是这样,那么这将是:
for (i = 0; i < itest.n; i++)
printf("%lld\n", itest.counter[i].counter);
在这种情况下,功能也应该有所改变。
打印不正确。 'itest.counter'是一个指针。 – 2011-04-27 16:34:08
哦......我的不好。纠正。 – Iustin 2011-04-27 16:35:06
你会得到什么错误? – Joe 2011-04-27 16:29:00
没关系,修复了所提供的帮助中的大部分错误谢谢 – Jono 2011-04-27 16:40:17
P.S. @Jono它会更好地upvote有用的答案,并回答你接受:) – 2011-04-28 06:57:42