2013-04-04 137 views
-1

此代碼:如何將二維數組的一部分複製到一維數組中?

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
int arr[3][3] = { 
        1,2,3, 
        4,5,6, 
        7,8,9 
       }; 


int *arry = (int*)malloc(3 * sizeof(int)); 
*arry = memcpy(arry, arr[1], 3 *sizeof(int)); 

int t; 
for(t = 0 ; t < 3 ; t++) 
    { 
     printf("\n"); 
     printf("%d \t", arry[t]); 
    } 
} 

是生產這樣的輸出:
過程返回3段(0x3)執行時間:0.011小號
按任意鍵繼續。

爲什麼它不能正確複製第一個值?

+0

*** ***二維修正 – 2013-04-04 14:53:24

+0

..謝謝 – 2013-04-04 14:57:32

回答

3

它被正確拷貝的第一個值,但

*arry = memcpy(arry, arr[1], 3 *sizeof(int)); 

您正在使用的memcpy返回值覆蓋它。

只需撥打

memcpy(arry, arr[1], 3 *sizeof(int)); 

,或者如果你要檢查它(毫無意義,因爲memcpy返回第一個參數)的返回值分配給不同的變量。

+0

感謝哇的驚人的快速,準確的響應+1 – 2013-04-04 14:53:54

+0

你應該接受的答案是正確的;) – Boumbles 2013-04-04 15:40:14

0

memcpy返回一個void *。

您正在將memcpy返回的void *賦值給arry所指向的值。嘗試讀取該值時,這會給你一個奇怪的值。只需調用的memcpy

memcpy(arry, arr[1], 3 * sizeof(int)); 
相關問題