How to assign some part of dynamic array to whole static array
The size of dynamic array is the twice the size of stat开发者_JAVA技巧ic array. I want to assign the values which starts from (N/2)-1 to N-1 of dynamic array to whole static array.
The only way is copying the values with a loop?
My code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int N=100, pSize=4, lSize, i;
double *A;
lSize=N/sqrt(pSize);
/* memory allocation */
A=(double*)malloc(sizeof(double)*N);
double B[lSize];
/* memory allocation has been done */
/* initilize arrays */
for(i=0; i<lSize; i++){
B[i]=rand()% 10;
}
A=B;
for (i=0; i<lSize; i++){
fprintf(stdout,"%f\n", A[i]);
}
return 0;
}
You can use the memcpy function to copy the data. For your example you want to copy the last half of A to B so could do something like:
memcpy(&B[0], &A[lSize-1], lSize * sizeof(double));
Note: On the MinGW compiler I was using, it was requiring that I declare the destination as &B[0], I thought I could get away with just B. It may be due to configuration I have (I don't use the C compiler all that much, normally just use g++ for quick C++ test cases).
You can use memcpy to copy contiguous chunks of memory around.
Your program leaks your allocation, which is probably bad - is that A=B
intended to be where you would put the code that copies the array?
It may be possible, depending on your architecture, to do a copy without a CPU loop (via a call to a DMA engine or something). In standard C, you have no choice but to loop. You can either do it yourself or you can call memcpy(3)
, memmove(3)
, or bcopy(3)
if you prefer to use the library's implementations.
As said, you need to use memcpy:
#define N 100
int staticarray[N];
int *pointer = (int*) malloc( sizeof(int)*N*2 );
memcpy( staticarray, (pointer + ((N/2) - 1)), sizeof(int)*N );
精彩评论