C++,exe在执行过程中已停止工作

C++ , exe has stopped working during execution

本文关键字:过程中 停止工作 执行 exe C++      更新时间:2023-10-16

我制作了一个小程序,可以使用合并排序算法合并两个数组,但令人惊讶的是,它在执行时会停止工作。。。它没有任何编译错误。

#include<iostream> 
#include<array> 
using namespace std;
int main()
{
    // below are declarations of two single dimensional arrays and two variables
    int n1,n2,t1,t2,t3;
    int l1 [5] = {2,1,4,3,5};
    int l2 [5] = {8,6,7,9,10};
    int l3 [10];
    n1 = l1[4] - l1[0] +1;
    n2 = l2[4] - l2[0] +1;   

   //below are the declaration and initialization of two pointers
     t1 = l1[0];
     t2 = l2[0];
     t3 = l3[0];

      while((n1>0) && (n2>0) )
     {
         if (l1[t1] < l2[t2])
         {
             l3[t3] = l1[t1]; 
             t1++;
             t3++;
             n1--;
             cout<<l3[t3]<<endl;
          }
          else
            l3[t3] = l2[t2];
          t2++;
          t3++;
          n2--;
     } 
 }

我仍然没有决定程序的输出

您对指针非常困惑。此:

n1 = l1[4] - l1[0] + 1;

l1[4],减去l1[0]

n1 = sizeof l1 / sizeof l1[0];

类似地,这个:

t1 = l1[0];

不构成"指针"-t1只是一个int,它包含l1[0],而不是它的地址。正如评论中所指出的,即使它是一个指针,你也不能将其用作索引。你真正想要的是:

t1 = 0;

最后,这个:

while( (n1 > 0) && (n2 > 0) )

将在通过一个数组后停止。你想要的是:

while( (n1 > 0) || (n2 > 0) )

尽管如果CCD_ 9包含任何高于CCD_。

这是你的程序的一个修改版本,它实现了你的算法:

#include <iostream>
int main()
{
    int l1[5] = {2, 1, 4, 3, 5};
    int l2[5] = {8, 6, 7, 9, 10};
    int l3[10] = {0};
    int n1 = sizeof l1 / sizeof l1[0];
    int n2 = sizeof l2 / sizeof l2[0];
    int t1 = 0, t2 = 0, t3 = 0;
    while ( (n1 > 0) || (n2 > 0) ) {
        if ( l1[t1] < l2[t2] ) {
            l3[t3++] = l1[t1++];
            --n1;
        }
        else {
            l3[t3++] = l2[t2++];
            --n2;
        }
    }
    for ( int i = 0; i < sizeof l3 / sizeof l3[0]; ++i ) {
        std::cout << l3[i] << std::endl;
    }
    return 0;
}

输出:

paul@horus:~/src/sandbox$ ./ms
2
1
4
3
5
8
6
7
9
10
paul@horus:~/src/sandbox$ 

显然,在实现时,您的算法会合并这两个列表,但如果它们最初没有排序,那么您就不会得到排序的列表。如果你真的想得到一个排序的列表,那么你还有更多的工作要做。此外,如上所述,你的算法通常不会对大多数数组正确工作。