2011-11-04 79 views
3

我有一個像分配結構

struct T { 
    int *baseofint 
}Tstruct, *pTstruct; 

int one; 
pTstruct pointer; 

一個struct現在我想定義

one = pointer.baseofint; //got filled with an integer; 
error message: **operator is not equal to operand** 

我也試過

one = *(pointer.baseofint); 
error message:**operand of * is no pointer* 

也許有人可以幫助,謝謝。

回答

1

首先,我不認爲下面的代碼是什麼你認爲它是:

struct T { 
    int *baseofint 
}Tstruct, *pTstruct; 

int one; 
pTstruct pointer; 

你聲明的結構類型struct T,並創建一個實例它稱爲Tstruct和指針它叫做pTstruct。但那些不是你創建的類型,而是變量。這使得pTstruct pointer;無效的代碼了。你可能是打算是一個typedef:

typedef struct T { 
    int *baseofint; 
} Tstruct, *pTstruct; 

...使Tstruct相當於struct T,並pTstruct相當於struct T *

用於訪問和取消引用baseofint場,這是稍有不同,這取決於您是否正在通過指針或不訪問...但這裏是如何:

Tstruct ts;   // a Tstruct instance 
pTstruct pts = &ts; // a pTstruct -- being pointed at ts 

/* ...some code that points ts.baseofint at 
* an int or array of int goes here... */ 

/* with * operator... */ 
int one = *(ts.baseofint); // via struct, eg. a Tstruct 
int oneb = *(pts->baseofint); // via pointer, eg. a pTstruct 

/* with array brackets... */ 
int onec = ts.baseofint[0]; // via Tstruct 
int oned = pts->baseofint[0]; // via pTstruct 
0

你可能想*(pointer->baseofint)

0

應該*pointer->baseofint

0

您需要使用->通過指針訪問結構成員。下面的兩個表達式是等效的:

pointer->baseofint 
(*pointer).baseofint 

在您的情況,您需要取消引用baseofint還有:

one = *pointer->baseofint; 

你剛打的,爲什麼這是一個壞主意,隱藏一個很好的例子類型是指針的事實。

我想你正在使用一個基於你的代碼沒有typedef的C++編譯器 - 你可能最終也會導致你自己的問題。

1

pTstruct是指向一個結構。該結構包含一個指向int的指針。所以你需要將它們解除引用。嘗試:

*((*pointer).baseofint) 

還要注意

p->x 

(*p).x 

的縮寫,所以

*(pointer->baseofint) 

是有效的,以及(少難以閱讀)。