2012-03-04 96 views
2

我有一個基本問題。現在我應該足夠了解指針。我看到它的方式configData是鏈接列表中的第一個鏈接(類型爲struct config),而procNames是指向類型爲struct config的鏈接列表中的第一個鏈接的指針。所以如果我想說procNames等於configData,那麼我需要訪問指向configData的指針*configData。無論如何,我想我失去了一些東西。任何人都看到了問題?另外,我得到了一個錯誤:錯誤:invalid type argument of unary ‘*’ (have ‘struct config’)指針ABC。錯誤:一元'*'的無效類型參數(有'結構配置')

struct config_line { 
    char name[MAX_WORD]; 
    int time; 
}; 

struct config { 
    struct config_line *lines; 
    int count; 
}; 

//global variable 
struct config configData; 
//local variable 
struct config *procNames; 
//the problem (done locally) 
procNames = *configData; 

回答

3

我想你想

procNames = &configData; 

這會將指針procNames的結構configData的地址。

您可以使用

procNames->count 
procNames->lines[i].name // Pointer to the 1st char of the name in the i'th config_line structure 

configData.count 
configData.lines[i].name 

記住訪問的元素,因爲lines本身就是一個指針,你需要爲每個config_line結構分配內存:

struct config_line thisLine; // Declare a structure 
procNames->lines = &thisLine; // Point to it 

// Declare a pointer to an array of structures, allocate memory for the structures 
struct config_line *linePtr = malloc(NUM_STRUCTS * sizeof(struct config_line)); 
procName->lines[i] = *linePtr; // Points to 1st structure in the array 
+0

不會是procName-> lines [i] = * linePtr? – 2012-03-05 00:03:37

+1

@PaulKar。是。好 - 趕快 - 謝謝! – 2012-03-05 02:15:32

2

根據你的你正在嘗試做的說明,你需要採取configData的地址(寫在最後一行& configData)。在最後一行中你要做的是取消引用configData,編譯器不會讓你這麼做,因爲configData不是一個指針(它不會存儲地址)。

錯誤信息對此很清楚。 Unary *將單個指針作爲參數,但使用類型爲struct config的參數,而不是指針。

相關問題