It is necessary in the one-dimensional (dynamic) array to replace the last of the zero elements with three zeros. Here is the program, it works. True, if there are two or more zeros in the array, the replacement is performed with the first zero, but with the last one.

#include "stdafx.h" #include<iostream> using namespace std; void input(int *a,int n); void print(int *a,int n); void insert(int *a,int &n,int &i); void Poisk(int *a,int n,int &i); int _tmain(int argc, _TCHAR* argv[]) { int n,i; cin>>n; int *a=new int [n]; input(a,n); Poisk(a,n,i); insert(a,n,i); print(a,n); system("Pause"); return 0; } void input(int *a,int n) { int i; for(i=0;i<n;i++) cin>>a[i]; } void print(int *a,int n) { int i; for(i=0;i<n;i++) cout<<a[i]<<" "; } void Poisk(int *a,int n,int &i) { int j; for(j=n;j>-1;j--) if(a[j]==0) i=j; } void insert(int *a,int &n,int &i) { int j;int k; Poisk(a,n,i); for(j=n-1;j>i;j--) swap(a[j],a[j+1]); ++n; a[i+1]=0; for(k=n-1;k>i+1;k--) swap(a[k],a[k+1]); ++n; a[i+2]=0; } 

    1 answer 1

    First, it is highly recommended to document (comment) the code.

    Secondly, you already in the function Poisk found the last zero element of the dynamic array. And they wrote it down to the variable i in the main . By the way, I wonder how the program will behave, if in principle there will not be a zero element!? So call Poisk(a,n,i); in the insert function is superfluous.

    Third, check the algorithm of the function f-insert - it should "stretch" the dynamic array to an additional two elements and shift all the elements after the last zero to the end of the array. Not explicitly allocated memory can not be used, otherwise the program will be unpredictable. That's exactly what happens. You need to use a structure like:

     int *a = new int [n]; // Π²Ρ‹Π΄Π΅Π»ΠΈΠ»ΠΈ ΠΏΠ°ΠΌΡΡ‚ΡŒ ΠΏΠΎΠ΄ массив int Π½Π° n элСмСнтов ... int *b = new int [n + 2]; // Π²Ρ‹Π΄Π΅Π»ΠΈΠ»ΠΈ ΠΏΠ°ΠΌΡΡ‚ΡŒ ΠΏΠΎΠ΄ массив Π½Π° n+2 элСмСнта for (int i = 0; i < j; i++) // скопируСм j элСмСнтов b[i] = a[i]; ... // здСсь Π΄Π΅Π»Π°Π΅ΠΌ ΠΏΠΎΠ»Π΅Π·Π½Ρ‹Π΅ Π²Π΅Ρ‰ΠΈ for (;i < n; i++) // ΠΏΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠΈΠ»ΠΈ ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ b[i + 2] = a[i;] delete a[]; // освободили ΠΏΠ°ΠΌΡΡ‚ΡŒ ΠΈΠ· ΠΏΠΎΠ΄ старого массива a = b; // помСняСм мСстами a ΠΈ b =) b = NULL; // b дальшС ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ Π½Π΅ стоит! ... delete a[]; // освободили ΠΏΠ°ΠΌΡΡ‚ΡŒ 

    Fourth, it is highly desirable to closely monitor the allocation of memory. Do not forget that each allocated block of memory must be released.

    Fifth, system("pause") is not the best way to make a delay in the program. Try using the getch() function or while (!kbhit()) construct. Well, or as an option, you can simply add any keyboard input to the end of the program =)