2015-10-15 137 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