L'ultimo
L'ultimo

Reputation: 561

C: add all the element of an array into another one

Is there a way in C to copy all the elements of an array into another one, without parsing all the elements of the array to copy? Could I use pointers? Because I know that a function can automatically take a certain number of element of an array just saying the index of the first element, so probably (?) I can do something similar...

For example if I have this two arrays:

int array[10];
int tocopy[3];

and I say something like:

array[0] = tocopy

it automatically fill also array[1] and array[2]

Is this possible?

Upvotes: 2

Views: 126

Answers (2)

pmg
pmg

Reputation: 108986

Your best bet might well be a for loop. You can make a function to "hide" details

void arrcopy(int *restrict dst, int dstindex, const int *restrict src, int srcindex, int len) {
    for (int k = 0; k < len; k++) {
        dst[dstindex + k] = src[srcindex + k];
    }
}

And you'd call it like this, for your example of copying the 1st three elements of tocopy to the 1st three elements of array

arrcopy(array, 0, tocopy, 0, 3); // array[0,1,2] = tocopy[0,1,2]

To copy the 2nd, 3rd, and 4th elements of tocopy (assuming they exist) to elements 6th, 7th, and 8th of array you would call the function like this

arrcopy(array, 5, tocopy, 1, 3); // array[5,6,7] = tocopy[1,2,3]

Of course, always make sure to not go over array bounds.

Upvotes: 1

jfMR
jfMR

Reputation: 24788

You could use memmove() or, if the arrays do not overlap, memcpy():

void *memmove(void *dest, const void *src, size_t n);
void *memcpy(void *dest, const void *src, size_t n);

For example:

memmove(array, tocopy, sizeof(tocopy);

would be like doing:

array[0] = tocopy[0];
array[1] = tocopy[1];
array[2] = tocopy[2];

Note

As suggested in the comments, be also aware of not to exceed the array bounds when using these functions, i.e.: either reading or writing outside the memory allocated for the array.

Upvotes: 5

Related Questions