Reputation: 3
Using memcpy(), I want to copy part of an array to another one where the source array is a double-pointer array. Is there a workaround to implement such a copying process without changing the double pointer?
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.
Upvotes: 0
Views: 1627
Reputation: 16607
Here is a simple example to do that -
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);
}
Upvotes: 1