Reputation: 223
Default struct given:
struct counter {
long long counter;
};
struct instruction {
struct counter *counter;
int repetitions;
void(*work_fn)(long long*);
};
static void increment(long long *n){
n++;
}
My line:
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?
So I am trying to get those three things working.
Thanks
Upvotes: 2
Views: 729
Reputation: 1260
Yes it does. But maybe it is more clear like this:
iter.counter = &ctest[0];
itest.work_fn = increment;
printf("%lld\n", itest.counter->counter);
That is if you plan to have only one counter. From your code you want multiple and maybe you should store the number in struct instruction. If so, then it would be:
for (i = 0; i < itest.n; i++)
printf("%lld\n", itest.counter[i].counter);
In this case the function should also be changed.
Upvotes: 0
Reputation: 168876
itest.counter = ctest; // This actually points itest.counter to ctest[0] right?
Right. itest.counter == &ctest[0]
. Also, itest.counter[0]
refers directly to the first ctest object, itest.counter[1]
refers the 2nd, etc.
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
Upvotes: 1
Reputation: 11108
void f(long long *)
) and here write itest.work_fn = f;
for(int i = 0; i < n; ++i) printf("%lld\n", itest.counter[i].counter);
Upvotes: 0