2011-04-30 47 views
-3

我有一個函數傳遞一個結構,而不是在arr本身上進行位操作,我想創建副本。如何製作無符號整數數組的元素的副本以進行位操作?複製位操作的指針

unsigned int * arr = cs->arr; // cs->arr is set as unsigned int * arr; 
unsigned int copy; 
memcpy(copy,arr[0], sizeof(unsigned int)); // Copy into copy the first element, for now 
int i = 0; 
while(copy != 0) 
{  
    i += copy & 1; 
    copy >>= 1; 
} 
return i; 

謝謝!

+0

您已經將它複製到'copy'中,那麼怎麼回事?你在尋找更好的方法? copy = arr [0]; – atoMerz 2011-04-30 07:30:02

+0

問題:「我如何擴展我所發佈的用於處理'arr'的所有元素而不是第一個元素的代碼」? – 2011-04-30 07:33:33

回答

1

你不需要memcopy。一個簡單的數組訪問就足夠了:

unsigned int copy = cs->arr[0]; 
int i = 0; 
while(copy != 0) 
{   
    i += copy & 1; 
    copy >>= 1; 
} 
return i; 
0
copy = arr[0]; 

是所有需要的。 copy將具有與arr[0]相同的值,但不會以任何其他方式鏈接到它。 (即修改copy不會改變arr[0])。