I have 2 arrays with coordinates and i want to copy them into one array. I used 2 for loops and its working, but i want to know, if i could do it without them, i dont know how to use memcpy in this situation. Here is my code:
int *join(int *first, int *second,int num, int size) {
int *path= NULL;
int i = 0 , j = 0;
path = (int*) malloc (2*size*sizeof(int));
for(i = 0 ; i < num; i++) {
path[i * 2] = first[i * 2];
path[i * 2 + 1] = first[i * 2 + 1];
}
for(i = num; i < size ; i++) {
path[(i*2)] = second[(j+1)*2];
path[(i*2)+1] = second[(j+1)*2 +1];
j++;
}
return path;
}
malloc()and family inC..path[(i*2)+1]writes to invalid memory with the last iteration.num,numis describing the number ofintpairs infirst, whilesizedescribes the total number of pairs in the result (that is, the number of pairs infirstandsecondcombined). The variable names are less than helpful I'll admit.2 * sizeints, so valid indices run from0to2 * size - 1inclusive. On the last iteration,iissize - 1, soi * 2 + 1is(size - 1) * 2 + 1which works out to2 * size - 1.int *new_arr = join(old_1, old_2, num_old_1, num_old_1 + num_old_2)would tell us a lot about how it is supposed to work.