2011-04-27 171 views
2
給出

默認結構: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? 

所以我試圖讓這三樣東西的工作。

感謝

+0

你會得到什麼錯誤? – Joe 2011-04-27 16:29:00

+0

沒關係,修復了所提供的幫助中的大部分錯誤謝謝 – Jono 2011-04-27 16:40:17

+0

P.S. @Jono它會更好地upvote有用的答案,並回答你接受:) – 2011-04-28 06:57:42

回答

1

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 
+0

如何在函數增量中傳遞n? itest.work_fn =增量(n); ? – Jono 2011-04-27 16:39:25

+0

@Jono:您在賦值時不傳遞參數,而只是函數代碼的起始地址。當你通過指針間接調用它時傳遞參數:'itest.work_fn(n)'。 – 2011-04-27 16:46:14

+0

謝謝!!!!!!!!! – Jono 2011-04-27 16:51:50

0
  1. 這指向CTEST的ADDRES。 (這是相同的,因爲它的第一個元素的ADDRES)
  2. 你應該申報蒙山相同的簽字:一些功能(比如void f(long long *)),在這裏寫itest.work_fn = f;
  3. for(int i = 0; i < n; ++i) printf("%lld\n", itest.counter[i].counter);
+0

static void increment(long long * n){ n ++; } 說如果我想使用這個功能? itest.work_fn =增量//那麼n呢?我如何通過它? – Jono 2011-04-27 16:33:30

+0

你可以調用'itest.work_fn(n);'這會增加你的n。 – 2011-04-27 16:48:42

+0

沒有。只是'itest.work_fn =增量'。 – 2011-04-27 16:51:17

0

是它。但也許它是這樣更清楚:

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); 

在這種情況下,功能也應該有所改變。

+0

打印不正確。 'itest.counter'是一個指針。 – 2011-04-27 16:34:08

+0

哦......我的不好。糾正。 – Iustin 2011-04-27 16:35:06