Jono
Jono

Reputation: 223

C Struct Pointers

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

Answers (3)

Iustin
Iustin

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

Robᵩ
Robᵩ

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

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11108

  1. This points to addres of ctest. (which is same as addres of it's first element)
  2. You should declare some function whith same signatur (say void f(long long *)) and here write itest.work_fn = f;
  3. for(int i = 0; i < n; ++i) printf("%lld\n", itest.counter[i].counter);

Upvotes: 0

Related Questions