2012-03-30 84 views
1

我的這段代碼的目標是創建一個1000個位置的數組,其中包含一個包含一個int(用作計數器)的結構和一個初始化爲100個位置數組的嵌套結構體。我的設計是否正確?是否可以創建一個嵌套的結構數組?怎麼樣?

由於在我試圖實現一個由100行100列的兩維表,其中這100行每個都有前面提到的int用作計數器/索引變量,並且100行中的每個位置數組由嵌套結構體組成! 這是我走到這一步:

#define DATA_MAX 1000 
#define MAX_CHAR_TIPO_MOV 60 
#define MAX_CHAR_DESCRICAO 60 
#define MAX_MOVIMENTOS 100 
#define BUFFLEN 1024 

char buffer[BUFFLEN]; 

typedef struct{ 
    int montante; 
    int data; 
    int periodicidade; 
    char tipo[MAX_CHAR_TIPO_MOV]; 
    char descricao[MAX_CHAR_DESCRICAO]; 
}sistema; 

typedef struct{ 
int indice; 
struct sistema tabela[MAX_MOVIMENTOS]; /* Compiler gives me an error here: array type has incomplete element type */ 
}movimentos; 

movimentos c[DATA_MAX]; 

/* Function to initialize arrays/structs in order to eliminate junk */ 


void inicializarfc(movimentos c[]) 
{ 
    int i, j; 
//percorre o vector estrutura 
for(i=0; i<DATA_MAX; i++) 
    for(j=0; j<MAX_MOVIMENTOS; j++) 
{ 
    c[i].[j].data = -1; 
    c[i].[j].montante = -1; 
    c[i].[j].periodicidade = -1; 
    memset((c[i].[j].tipo), ' ', sizeof(c[i].[j].tipo)); 
    memset((c[i].[j].descricao), ' ', sizeof(c[i].[j].descricao)); 
    } 
} 

如果確實有可能創造我問什麼,我應該如何去訪問結構成員? 使用GCC編譯W7中的Codeblocks 10.05。

回答

1

您不需要在typedef前面使用struct關鍵字。

只是說:

sistema tabela[MAX_MOVIMENTOS]; 

要訪問的成員,只是說:

movimentos m; 
/* initialize data */ 
int x = m.tabela[0].montante; // accesses montante field of tabela[0] 
0

讓我們來看看你的聲明:

typedef struct{ 
    int montante; 
    int data; 
    int periodicidade; 
    char tipo[MAX_CHAR_TIPO_MOV]; 
    char descricao[MAX_CHAR_DESCRICAO]; 
}sistema; 

typedef struct{ 
    int indice; 
    struct sistema tabela[MAX_MOVIMENTOS]; 
}movimentos; 

的問題是,你尋找一個名爲struct sistema的類型,但是你還沒有聲明類型;相反,您聲明瞭一個匿名結構類型併爲其創建了一個typedef名稱sistema。要訪問一個名爲struct sistema類型,你就必須提供在定義的結構標籤:

struct sistema { ... }; 

的結構標籤sistema和typedef名sistema生活在不同的命名空間;你可以寫

typedef struct sistema { ... } sistema; 

,並同時使用sistemastruct sistema互換,儘管這可能會造成混亂。

在這種情況下,最簡單的做法是改變

struct sistema tabela[MAX_MOVIMENTOS]; 

sistema tabela[MAX_MOVIMENTOS]; 

movimentos結構類型。

相關問題