2015-10-15 135 views
0

使用memcpy(),我想複製部分數組到另一個源數組是雙指針數組的地方。是否有解決方案來實現這樣的複製過程沒有更改雙指針?兩個不同指針之間的memcpy()

int **p; 
p= malloc(sizeof(int *)); 
p= malloc(5 * sizeof(int)); 

int *arr; 
arr= malloc(5 * sizeof(int)); 

for(i = 0; i < 5; i++){ 
    p[i] = 1; 
} 

memcpy(arr, (2+p) , 3*sizeof(int)); // I want to start copying 3 elements starting from the third position of the src. 
+0

你不分配內存以'arr'。 – ameyCU

+0

對不起,這是一個錯誤。我的意思是arr –

+4

'p = malloc(sizeof(int *)); p = malloc(5 * sizeof(int));' - 這看起來不正確... –

回答

1

下面是一個簡單的例子來做到這一點 -

int main(void){ 
    int **p; 
    int *arr,i; 
    p= malloc(sizeof(int *));  // allocate memory for one int * 
    p[0]=malloc(5*sizeof(int));  // allocate memory to int * 
    for(i = 0; i < 5; i++){ 
     p[0][i] = i+1;    // assign values 
    }  
    arr= malloc(5 * sizeof(int));  // allocate memory to arr 
    memcpy(arr,&p[0][2],3*sizeof(int)); // copy last 3 elements to arr 

    for(i=0;i<3;i++){    
    printf("%d",arr[i]);    // print arr 
    } 
    free(p[0]); 
    free(p); 
    free(arr); 

} 

Output

+0

這是正確的。謝謝:) –

+0

@JacksonArms歡迎:) – ameyCU