2021年3月17日星期三

Concatenating two arrays and inserting a new element to array

So my goal is to join two Arrays together and insert the new size of the new array in the beginning of the array. For example if

Arr1 = {5, 1,2,3,4}      and Arr2 = {5, 10, 20, 30, 40 };    NewArr = { 11, 5, 1, 2, 3, 4, 5, 10, 20, 30, 40 }  

However, when I run my code I get

NewArr = {11 1 2 3 4 10 20 30 40 -12851 -12851}  

It looks like I'm losing the first elements in both of my arrays. Here's my code.

short int* ConcatArray(short int* a1, short int* a2) {      //size of array 1      int n = *(a1 + 0);      //size of array 2      int m = *(a2 + 0);      int i;      int size = n + m;        short int* newArr = new short int[n + m];        // increase the size by 1      size++;        // shift elements forward       for (i = size; i >= 1; i--)          *(newArr + i) = *(newArr + i - 1);        // insert x at pos       *(newArr + 1 - 1) = size;        // Create new Array       for (i = 1; i < n; i++) {          *(newArr + i) = *(a1 + i);      }            for (int j = 1; j < m; j++, i++) {          *(newArr + i) = *(a2 + j);      }              return newArr;  }  
https://stackoverflow.com/questions/66683886/concatenating-two-arrays-and-inserting-a-new-element-to-array March 18, 2021 at 10:22AM

没有评论:

发表评论