1

The size of dynamic array is the twice the size of static 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; } 

4 Answers 4

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

You'd better copy more than lSize bytes if you want the whole array to be full. A double is usually bigger than 1 byte.
Good catch, this site needs peer code review before answers are committed :)
0

You can use memcpy to copy contiguous chunks of memory around.

Comments

0

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.

1 Comment

Yes it is intended for copying process and this is a sample code to see the results. my acctual code is for parallel programming project which is a matrix-vector multiplication in cartesian topology. i'm sending the multiplication results with vector derived type.
0

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 ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.