2010-02-02 87 views
1
#include <stdio.h> 
#include <stdlib.h> 

typedef int element; 

struct cell { 
    element e; 
    struct cell *p; 
}; 
typedef struct cell* CELL; 

int main() { 
    CELL* p; 
    p = (CELL*) malloc (sizeof(struct cell)); 
    p->e = 8;  /* This ain't working */ 
    *p.e = 8;  /* This doesn't help anything either */ 

    return 0; 
} 

我剛開始接觸malloc,我剛剛作出了一個指針到新創建的CELL,這是一個struct。現在我試圖用一些價值來填補它,但是我受到了一個不友好的「對成員e的請求」的歡迎,而不是一個結構或聯盟。「我確實指向了一個包含e成員的struct,或者至少,這就是我想我做到了。爲什麼會失敗?爲什麼我不能通過它的指針訪問這個結構體?

回答

6

變化

cel* p; 
p = (CELL*) malloc (sizeof(struct cell)); 

*p.e = 8; 

struct cell* p; // or CELL p; 
p = (CELL) malloc (sizeof(struct cell)); 

(*p).e = 8; // . has higher precedence than * 
3

由於該類型定義爲指針類型,我認爲要投它作爲CELL不是CELL *。

9

我認爲這很好地說明了一個良好的C風格的規則 - 不要創建隱藏事物是指針的事實的typedefs。

0

我解決這個:

#include <stdio.h> 
#include <stdlib.h> 

typedef int element; 

struct cell { 
    element e; 
    struct cell *p; 
}; 
typedef struct cell* CELL; 

int main() { 
    CELL p; 
    p = (CELL) malloc (sizeof(struct cell)); 
    p->e = 8; 
    (*p).e = 8; 

    return 0; 
} 

謝謝大家。

1

只是爲了通過被明確完成其他精細答案:

在你的代碼,你定義CELL類型是「指向一個struct cell」。然後,您創建本地變量pCELL *,即「指向類型爲CELL的值的指針」。換句話說,一個指向指針的指針。這太過分了。 「->」操作符只遵循一個間接級別,而不是兩個。

相關問題