prazza - 1 year ago 201
C++ Question

C++ int massives

I tried to solve well-known task " pile of stones " with sorting and throwing weights to different massives. But programm works weird now, it shows correct massives and summs of elements in debug mode , but in Run it shows different, incorrect answer.

here's the code:

``````void Sort(int pile[],int N)
{
int tmp=0;
for(int i=0; i<N-1; i++)
{
for(int j=0; j<N-i-1; j++)
{
if(pile[j]<pile[j+1])
{
tmp=pile[j];
pile[j]=pile[j+1];
pile[j+1]=tmp;
}
}
}
}

void Show(int pile[], int N)
{
cout<<endl;
for(int i=0; i<N; i++)
{
cout<<pile[i]<<"  ";
}
}

void Alternate()
{
while(1)
{
int *pile , *LHeap, *RHeap, N=0, RCount=0, LCount=0, RIter=1,LIter=1;
cout<<Rus("\nВведите количество камней: ");
cin>>N;
///dynamic memory for N-size mass
pile=new int(N);
LHeap=new int(N);
RHeap=new int(N);
///App close if 0 size of mass entered
if(N==0) break;
else
{
cout<<Rus("Введите вес всех камней\n");
for(int i=0; i<N; i++)
{
cin>>pile[i];
}

Sort(pile, N);
Show(pile, N);
///make first elements of heap's equal to 1 and 2 elements of pile
///Count'z to count the current size of mass
LHeap[0]=pile[0];
LCount+=pile[0];

RHeap[0]=pile[1];
RCount+=pile[1];
///fulfill both massive
for(int i=2; i<N; i++)
{
if(LCount<=RCount)
{
LHeap[LIter]=pile[i];
LIter++;
LCount+=pile[i];
}
else
{
RHeap[RIter]=pile[i];
RIter++;
RCount+=pile[i];
}
}

cout<<Rus("\nкуча 1: ");
Show(LHeap,LIter);
cout<<Rus("\nкуча 2: ");
Show(RHeap,RIter);
cout<<Rus("\nСумы в кучах: ")<<LCount<<"  "<<RCount<<endl;

}

}

}

int main()
{
//Primitive();
Alternate();
_getch();
return 0;
}
``````

You're getting different results because your program is undefined.

This

``````new int(N)
``````

allocates one `int` with the value `N`.
Indexing any index other than 0 from that pointer is undefined.

To allocate an array, use

``````new int[N]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download