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.
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.
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]
memcpyvoid * 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)
#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;
}
$ ./a.out
4=14
3=13
2=12
1=11
0=10
for(i=x, j=0; i<=y; i++, j++)
AnotherArray[j]= A[i];
memcpy(dest,&array[42],42)?memcpy(another, A + x, sizeof(*A)*(y-x));//It does not include y