2014-11-05 79 views
-1

我想小結構數組中的所有元素複製到更大的結構數組沒有從結構上我的代碼如下將結構數組複製到另一個更大的結構數組而無需單獨訪問元素?

這個問題在這裏copy smaller array into larger array問前先複製單個元素,但我找不到合適的reply.please幫助我

struct st 
{ 
    int i; 
    char ch[10]; 
}; 

int main() 
    { 
    struct st var[2]={1,"hello",2"bye"}; 
    struct st largevar[3]; 
    strcpy(largevar,var);// this is bad i guss but is there any way to copy without individual element access? 
    } 
+1

['memcpy'](http://linux.die.net/man/3/memcpy)? – IllusiveBrian 2014-11-05 16:44:19

回答

0

您應該使用memcpy(),如下所示,而不是strcpy()。

#include<stdio.h> 
#include<string.h> 

    struct st 
    { 
     int i; 
     char ch[10]; 
    }; 

    int main() 
     { 
      int i =0; 
     struct st var[2]={{1,"hello"},{2,"bye"}}; 
     struct st largevar[3]; 
     memcpy(largevar,var,sizeof(struct st) * 2); 
     for(i=0;i<2;i++) 
     printf("%d %s\n",largevar[i].i,largevar[i].ch); 
     return 0; 
     } 
1

你是不是很遠,但在memcpy正確的功能:strcpy副本空終止字符串,memcpy副本任意的內存塊:

你可以使用:

memcpy(largevar, var, sizeof(struc st) * 2);