2011-04-28 112 views
5
struct counter{ 
    long long counter; 
} 

struct instruction{ 
    struct counter *counter 
    int repetitions; 
    void (*work_fn)(long long *); 
}; 

int ncounter; //number of counters 
struct counter *counter; //counter array 

int nthreads; //number of threads 
int *ninstructions; //number of instructions 

struct instruction **instructions; 

這實際上是如何工作的?我遇到了**指針問題C雙指針

+2

最好不要將問題放在代碼行註釋中。 – takrl 2011-04-28 06:43:17

+3

如果您不知道C#是什麼,請不要使用C#標記C問題。 – BoltClock 2011-04-28 06:44:12

+0

請將您的問題放在代碼塊外面,否則人們不會看到它。我編輯了它,現在將其移出。 – 2011-04-28 06:44:32

回答

10

A **只是一個指向指針的指針。因此,在instruction*包含instruction結構的地址的情況下,instruction**包含instruction*的地址,其中包含instruction對象的地址。

要訪問instruction**指向的指針指向的instruction,您只需使用兩個星號而不是一個,如(**p).repetitions或類似內容。

你可以想像它是這樣的:但是

instruction* ----> instruction 
instruction** ----> instruction* ----> instruction 

記住,簡單地宣佈struct instruction** instructions;實際上並沒有創造一個instruction結構。它只是創建一個保存垃圾值的指針。你必須初始化:

struct instruction inst; 
// set members of inst... 
*instructions = &inst; 

... 

(*instructions)->repetitions++; // or whatever 

但是,它看起來像你使用instruction**指向的instruction*秒的陣列。要初始化數組,你需要一個for循環:

instructions = malloc(sizeof(struct instruction*) * num_of_arrays); 
for (i = 0; i < num_of_arrays; ++i) 
    instructions[i] = malloc(sizeof(struct instruction) * size_of_each_subarray); 

然後你就可以像訪問instructions[i]->datamember的元素。

+0

但是說我使用struct counter * counters並創建一個數組。當我訪問元素時,counter [i] - > counters .....不是那樣的東西?!?但是計數器*不是** – Jono 2011-04-28 07:56:33

+0

@Jono,如果你說'struct counter * counters',它就會指向一個'counter'。要訪問一個元素,你需要'counter [i] .something'。 '櫃檯[i]'給你一個'櫃檯'。但是,如果你做'struct counter ** counters',你必須執行'counters [i] - > something',注意' - >'而不是'.'。在這種情況下,'counters [i]'給你一個指向'counter'的指針,而不是實際的'counter'。 – 2011-04-28 14:28:46

1

struct instruction **instructions; // How does this actually works ? I am having trouble with ** pointers

我不知道真正的問題是什麼,但我會盡力回答這個問題。

雙指針是指向指針的指針。例如,它可以作爲指針數組來使用(如果相應地分配內存)。例如:

instructions = malloc(5*sizeof(struct instruction*)); 
for (int i = 0; i < 5; i++) 
    instructions[i] = malloc(sizeof(struct instruction)); 

而且你得到了很好的指向struct instruction的5個指針。使用這樣的:

instructions[0]->repetitions = 0; 
0

instructions是一個指針的指針struct instruction

這意味着*instructions會給你一個指向struct instruction的指針。這種結構通常用於創建指向某些複合類型的動態數組指針。