2013-04-23 112 views
-3

我怎樣才能使它工作?結構數組元素可以是隨機的,數組中的元素可以變化。我試圖創建一個指針,並分別分配每個記錄,但沒有運氣。c中的結構數組賦值

#include<stdio.h> 

typedef struct _str 
{ 
    int arraySize; 
    int a[10]; 
} str; 


int main() 
{ 
    str s[50]; 

    s[10] = {4, {1, 4, 5, 6}}; 
    s[20] = {3, {2, 7, 11}}; 
    s[30] = {3, {3, 8, 9}}; 

    return 0; 
} 
+0

)' ? – 2013-04-23 07:13:18

+0

你究竟需要什麼?請詳細說明。 – 2013-04-23 07:16:17

+0

@Koushik我跑了它,它顯示錯誤'預期表達式'{'token |' – 2013-04-23 07:19:04

回答

0

如果您想要決定運行時使用列表(Linkedlist或循環列表)中元素的數量而不是數組。看到http://www.cprogramming.com/tutorial/c/lesson15.html

或使用代碼類似於下面

typedef struct _str 
{ 
    int arraySize; 
    int *a; 
} str; 


int main() 
{ 
str s[50]; 

    s[0].arraySize =3; 
    s[0].a=(int *)malloc(sizeof(int)*s[0].arraySize) ; 
    s[0].a[0]=2; 
    s[0].a[1]=5; 
    s[0].a[2]=7; 


    return 0; 
} 
2

你正在做的就是確定結構什麼它已經宣佈 後,你只能分配一個struct它已經經過

結構可以聲明和初始化在一次的句子(我的意思是在dec laration)爲使

typedef struct _str 
{ 
    int arraySize; 
    int a[10]; 
} str; 

int main() 
{ 
    str s[10] = {{1,{2,3,4}},{2,{3,5,6}}....};// this is correct but impractical. 

//但這是錯誤的

s[1] = {1,{2,3,4}};// 

//你有所以你要`蘭特(要做到這一點

s[1].arraysize = 10; //explicitly assign each member 

    for(int i=0;i<s[1].arraysize;i++) 
    s[1].a[i] = value; 

}

+0

謝謝你的回答。我知道你的解決方案。如果可能的話,我試圖以更簡單的方式做。 – 2013-04-23 07:53:06

+0

@MeUnagi更簡單的方式是這個'str s [10] = {{1,{2,3,4}},{2,{3,5,6}} ....};'ofcouse simple in current上下文只是分割和初始化,而不是可讀性,生產力等。 – 2013-04-23 07:55:21