APP
APP

Reputation: 41

Copy array from certain position to another array in c

I have array A and i want to copy this array from position x till y to another array in C language. Please help in creating it in c.

Using memcpy copies array from beginning only. I want to copy from particular position to another position.

Upvotes: 3

Views: 14889

Answers (5)

Felix Quehl
Felix Quehl

Reputation: 823

Copy arrays with memcpy

void * memcpy (void * destination, void * source, size_t size)

The memcpy function copies an certain amount of bytes from a source memory location and writes them to a destinaction location. (Documentation)

Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int some_array[] = {10, 11, 12, 13, 14};
    
    int memory_amount = sizeof(some_array);
    int item_count = memory_amount / sizeof(some_array[0]);
    int *pointer = malloc(memory_amount);
    memcpy(pointer, &some_array, memory_amount);

    while (item_count--)
        printf("%d=%d\n", item_count, *(pointer + item_count));

    free(pointer);
    return 0;
}

Output

$ ./a.out 
4=14
3=13
2=12
1=11
0=10

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[5];

memcpy( b, a + 5, 5 * sizeof( int ) );

Also you can do this using an ordinary for loop

for ( int i = 0; i < 5; i++ ) b[i] = a[i+5];

Upvotes: 6

Pawan Kumar
Pawan Kumar

Reputation: 49

for(i=x, j=0; i<=y; i++, j++)
   AnotherArray[j]= A[i];

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74695

memcpy only copies from the beginning of an array if that's what address you pass it. The name of an array a is synonymous with the address of the first element &a[0], so if you do memcpy(dest, src, size), then the copy will be from the start of the array src.

Pointer arithmetic can be used to start the copy from a point further along in your array. For example, to copy 10 elements starting from element 2 in array src, you can do this:

size_t size = 10 * sizeof (int);
int * dest = malloc(size);
memcpy(dest, src + 2, size);  // or equivalently, &src[2]

Upvotes: 3

jxh
jxh

Reputation: 70502

Since you are copying into another array, you can use memcpy():

memcpy(another_array, array + x, (y - x) * sizeof(*array));

If you were copying into the same array, you should use memmove() instead.

memmove(array + z, array + x, (y - x) * sizeof(*array));

For each, the first parameter denotes the destination, and the functions assume the destination has enough space to accept the complete copy.

Upvotes: 4

Related Questions