Array insert 2 after every x passed as parameter

Given the array:
int numbers[]={-2,-1,3,2,-8,6,-10,-2,5,1}
the dimension and a certain number to look for as parameters to a function
i have to insert the number 2 into the array after every x given as a parameter
and return the number of insertions.
result example inserting 2 after every -2
Number of insertions: 2;
-2, 2, -1, 3, 2, -8,6,-10,-2,2,5,1
My code so far;
 ``1234567891011121314151617181920`` ``````int inserare(int v[], int n, int x) { int insertions=0; bool ok; do { ok=false; for(int i=0;ii;--j) { v[j]=v[j-1]; } v[i+1]=2; } } while(ok==true); return insertions; }``````

Last edited on
If you have an array of a set size, and you intend to write beyond the length of that array, you're going to have to make a new array of the correct length.

Alternatively, use a proper C++ container like a vector that will take care of its own size for you, and presents you with helpful insertion functions.
Why can't I use the same array? Increase the dimension of it by 1 each time. Move everything to the right then replace the duplicate number with 2?

I can only use what the teacher has teached so far. Basic stuff like in my solution.
Last edited on
 Why can't I use the same array?

Arrays exist in memory. They occupy "contiguous memory" - this simply means that the array is one long block in memory. The memory on either side of the array is available for other variables, and depending on how you've written your program, you can pretty much guarantee that the memory is being used for other variables. If you write beyond the length of an array, you will be writing over those other variables.

 Increase the dimension of it by 1 each time.

I don't see you increasing the size of the array in your code. You're just writing over it and then writing over the next bit of memory along as well, which is not part of the array.
Last edited on
Topic archived. No new replies allowed.