Hey. I was given the following problem to work out:
Assume the following integers are stored in an integer array: 2, 19, 22, 34, 55 , 89, 100, 201, 239, 397. Using pointers, write a function, Insert(), which accepts the integer array and a new integer as arguments and inserts the new integer in the correct order in the integer array. Testing your function by the following new
integers:
a[10] = {2, 19, 22, 34, 55 , 89, 100, 201, 239, 397 }
new number: 27; 210; 77.
I wrote up some (probably overly complicated) code for this and it runs correctly but after the program closes an error pops up that says "Stack around the variable 'Array' was corrupted". I tried searched for any incorrect value that I might have placed relating to the variable but I can't find anything. Here is the code, I would appreciate any help getting to the bottom of this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include "stdafx.h"
#include <iostream>
using namespace std;
int Insert(int*, int);
int main()
{
const int size=10;
int Array[size]={2, 19, 22, 34, 55, 89, 100, 201, 239, 397};
int newnum;
cout<<"Please enter a new integer to be placed into the array: "<<endl;
cin>>newnum;
*Array=Insert(Array, newnum);
cout<<"The new array is ";
for(int i2=0;i2<11;i2++){
cout<<*(Array+i2)<<", ";
}
cout<<endl;
system("pause");
return 0;
}
int Insert(int* ARR, int NEWNUM){
{
if(NEWNUM<*ARR){
for(int i=11;i>0;i--){
*(ARR+i)=*(ARR+i-1);
}
*ARR=NEWNUM;
}
else if(NEWNUM>=*(ARR) && NEWNUM<=*(ARR+1)){
for(int i=11;i>1;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+1)=NEWNUM;
}
else if(NEWNUM>=*(ARR+1) && NEWNUM<=*(ARR+2)){
for(int i=11;i>2;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+2)=NEWNUM;
}
else if(NEWNUM>=*(ARR+2) && NEWNUM<=*(ARR+3)){
for(int i=11;i>3;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+3)=NEWNUM;
}
else if(NEWNUM>=*(ARR+3) && NEWNUM<=*(ARR+4)){
for(int i=11;i>4;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+4)=NEWNUM;
}
else if(NEWNUM>=*(ARR+4) && NEWNUM<=*(ARR+5)){
for(int i=11;i>5;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+5)=NEWNUM;
}
else if(NEWNUM>=*(ARR+5) && NEWNUM<=*(ARR+6)){
for(int i=11;i>6;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+6)=NEWNUM;
}
else if(NEWNUM>=*(ARR+6) && NEWNUM<=*(ARR+7)){
for(int i=11;i>7;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+7)=NEWNUM;
}
else if(NEWNUM>=*(ARR+7) && NEWNUM<=*(ARR+8)){
for(int i=11;i>8;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+8)=NEWNUM;
}
else if(NEWNUM>=*(ARR+8) && NEWNUM<=*(ARR+9)){
for(int i=11;i>9;i--){
*(ARR+i)=*(ARR+i-1);
}
*(ARR+9)=NEWNUM;
}
else if(NEWNUM>*ARR){
*(ARR+10)=NEWNUM;
}
}
return *ARR;
}
|