2013-03-21 86 views
0

所以我試圖修改一些代碼,我需要創建一個結構數組。該結構聲明如下:創建一個結構數組

typedef struct header 
{ 
    int sample_rate; 
    int num_channels; 
    int bit_res; 
    int num_samples; 
    char *data; 
} header; 

typedef struct header* header_p; 

什麼是創建和使用此結構數組的正確方法?我試圖沿着線的東西:

header_p fileHeader; 
... 
fileHeader = (header_p)malloc(sizeof(header) * (argc-1)); 

這似乎是工作,但我不知道如何正確地訪問陣列。

編輯:(我的一些問題,不知何故砍掉的) 當我嘗試訪問像這樣的數組:

fileHeader[0] = function that returns header_p;

我得到以下編譯錯誤:

incompatible types when assigning to type ‘struct header’ from type ‘header_p’ 

編輯: (想通了) 在遵循Lundins的建議去除隱藏結構指針的愚蠢typedef之後,它很容易看到發生了什麼。那麼更容易看出,亞歷克斯是正確的需要取消我的指針。從技術上講,我會接受亞歷克斯的回答,那是我的問題。因爲它是一個指針

fileHeader[0].bit_res  = ... 
fileHeader[1].num_samples = ... 

,你與[]指數在尊重它:

+0

你想使用C或C++嗎? – Tushar 2013-03-21 07:27:51

+0

對於您標記的兩種語言,適當的答案完全不同。選一個。 – 2013-03-21 07:28:06

+0

我打算在C. – tgai 2013-03-21 07:29:51

回答

1

這裏:

fileHeader[0] = function that returns header_p; 

你忘了指針引用。

fileHeader[0] = *function_returning_header_p(); 
+0

轉換爲'(header_p)'是不必要的。 – Tushar 2013-03-21 07:38:08

+0

@Tushar,'malloc()'返回'void *'。 – Alex 2013-03-21 07:38:54

+0

正確,但請參閱:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Tushar 2013-03-21 07:40:08

0

你可以這樣訪問它。然後您訪問.的成員。

2

What is the correct way to create and use an array of this struct?

header* fileHeader; 

fileHeader = malloc(sizeof(header) * (argc-1)); 
  • 指針的typedef是沒有意義的,使你的程序無法讀取。
  • 投射malloc的結果沒有意義。
  • 您按照預期分配了sizeof(header)*自變量的數量,然後-1 字節而不是-1 自變量。觀察運算符優先級。這是一個錯誤,你正在分配太多的內存。
+0

所以你說的一切都很有道理,但我仍然無法訪問數組。我仍然收到我在我的問題中提到的相同的編譯錯誤。 – tgai 2013-03-21 07:42:57

+0

@Tarmon編譯器錯誤與多餘的指針typedef有關,這沒有任何意義。如果你刪除它,你也可能會刪除你的問題。 _Never_隱藏在typedefs後面的指針,它的風格很差。 – Lundin 2013-03-21 07:46:20

+0

好吧,誠實地說,我對typedef有點困惑,但我借用了一些代碼,它的工作原理讓我只用了它。我會回去嘗試清理,看看我的生活是否更容易。 – tgai 2013-03-21 07:48:50

相關問題