2010-11-18 18 views
0

我有這樣的結構:我該如何處理一系列結構?

#define sbuffer 128 
#define xbuffer 1024 

typedef struct{ 
    char name[sbuffer]; 
    char att[sbuffer]; 
    char type[sbuffer]; 
    int noOfVal; 
    int ints[xbuffer]; 
    double doubles[xbuffer]; 
    char *strings[xbuffer]; 
} variable; 

我需要從這個結構創建一個數組,我這樣做

variable *vars[512]; //is it right 

如果我想把一個字符串,我在S插入名稱,我這樣做:

char *s = "What Ever"; 
strcpy(vars[0]->name,s); 

但這不適合我,任何人都可以幫忙嗎?

回答

5

獲得該行擺脫*的:

variable *vars[512]; //is it right 

並使用點語法訪問結構體成員在strcpy

char *s = "What Ever"; 
strcpy(vars[0].name,s); 
+0

我把它拿出來,但我現在得到的strcpy函數的錯誤,, – 2010-11-18 02:07:26

+0

@Rami - 更新。 – 2010-11-18 02:09:53

+0

thx男人:),它的工作 – 2010-11-18 02:27:11

0

我認爲你需要使用

variable vars[512]; 

而不是

variable *vars[512] 
1

您已經分配的指針數組的結構,但沒有創建它們的實例(分配的內存)。你可以將它作爲一個結構數組(沒有指針),所以你不必擔心內存管理。

char *s = "What Ever"; 
variable vars[512]; /* an array of your structure */ 
strcpy(vars[0].name,s); /* <- use dot operator here since they are no longer pointers */ 

或者使用它(並初始化所有其它指針NULL)之前至少分配內存結構。

char *s = "What Ever"; 
variable *vars[512]; /* an array of pointers to your structure */ 
vars[0] = (variable *)malloc(sizeof(variable)); /* dynamically allocate the memory */ 
strcpy(vars[0]->name,s); /* <- used arrow operator since they are pointers */ 
0
variable *vars[512] = {NULL}; 

int i = 0; 

//i may get a value in some way 

if (NULL == vars[i]){ 
    vars[i] = (variable *)malloc(sizeof(struct variable)); 
} 
相關問題