2013-02-28 85 views
1

我想學習C.我創建了這個結構,我試圖從現有數組傳遞名稱到結構元素名稱[100]之一,我無法理解如何傳遞它?夥計們請幫助我,並指導我如何去做。如果有人能指導我一個好的結構教程(網上有很多,但只有基礎知識),這將是一個很大的幫助......謝謝。如何將數組元素傳遞給結構?

typedef struct new_st{ 

     char name[100]; 

     int icon_number; 

     float calculation; 

     }var; 

char arr_name[] = {「name1」, 「name1」, 「name1」, 「name1」 };/this lines throws error 


int main(){ 

var *ptr_var; 

New_var = malloc(sizeof(struct new_st)*100); 

strcpy(&arr_name[0], ptr_var[1].name);//this lines throws error 

return 0; 

} 
+1

New_var?你的意思是ptr_var?請給我們乾淨的代碼 – 2013-02-28 09:44:05

+0

請現在請它 – EmbeddedCrazy 2013-02-28 10:16:25

+0

它看起來你有錯誤的引號和不完整的評論(一個斜槓而不是兩個)。猜猜你應該更具體一些關於'..拋出這麼多錯誤..'。 – 2013-02-28 10:21:33

回答

2

使用strcpy()

strcpy(New_var[0].name, arr_name[0]);

忠告:不要malloc()

--edit將返回值的源代碼公佈後 -

你大概意思:strcpy(ptr_var[1].name, arr_name[0]);

這是假設是:

char *arr_name[] = {「name1」, 「name1」, 「name1」, 「name1」 };/*this lines throws error*/ 
1

我想你想要做的是這樣的:

var *ptr_var; 
ptr_var = malloc(sizeof(struct new_st) * 100); 

ptr_var[0].calculation = 1.5f; //assigning variable inside your struct 0 in your array of structs 
ptr_var[0].name = "Foobar"; 


strcpy(&arr_name[0], ptr_var[1].name); //copy string 
//Free memory at end of your program 
free(ptr_var); 
+0

'ptr_var [0]'只有在'ptr_var'被定義爲'var ** ptr_var'時才能工作 - 你也不應該使用malloc返回 – 2013-02-28 09:41:50

+0

@Aniket它是一個單維數組,AFAIK你可以像數組一樣訪問它們嗎? – 2013-02-28 09:42:50

+0

你是對的,當我再次考慮它時.. – 2013-02-28 09:44:47