You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio中数组append与merge函数输出异常问题求助

问题分析与修复

1. Append函数问题

错误原因:

  • 第二个循环起始索引错误:i = sizeA - 1 会覆盖arrayA的最后一个元素(索引sizeA-1),且循环次数多一次,导致访问arrayB的越界元素(j超出sizeB范围),最终出现未初始化的垃圾值。

修复方案:

直接通过sizeA + j计算arrayB元素在新数组中的位置,循环sizeB次即可,避免索引计算错误。

2. Merge函数问题

错误原因:

  • 索引错误:else分支中误写为arrayB[i],应该是arrayB[j];
  • 循环条件错误:sizeof(mergeArray)返回的是指针的大小(而非数组长度),导致循环提前终止;
  • 缺失剩余元素拷贝:当其中一个数组遍历完成后,未将另一个数组的剩余元素拷贝到结果数组中。

修复方案:

  • 修正索引为arrayB[j];
  • 循环条件改为i < sizeA && j < sizeB,直到其中一个数组遍历完成;
  • 添加两个循环分别拷贝arrayA和arrayB的剩余元素。

修正后的完整代码

#include <iostream>

using namespace std;

int* append(int*, int, int*, int);
int* merge(int*, int, int*, int);
void print(int*, int, const char*);

int main()
{
    int arrayA[] = { 11,33,55,77,99 };  // use other values for more tests
    int arrayB[] = { 22,44,66,88 };
    print(arrayA, 5, "Sorted array A: ");
    print(arrayB, 4, "Sorted array B: ");
    int* arrayC = append(arrayA, 5, arrayB, 4); // arrayC points to the appended array
    print(arrayC, 9, "Append B to A:  ");
    int* arrayD = merge(arrayA, 5, arrayB, 4);
    print(arrayD, 9, "Merge A to B:   ");
    delete[] arrayC;
    delete[] arrayD;

    return 0;

}

int* append(int* arrayA, int sizeA, int* arrayB, int sizeB)
{
    int num = sizeA + sizeB;
    int* appendArray = new int[num];

    // Copy elements from arrayA
    for (int i = 0; i < sizeA; i++)
    {
        appendArray[i] = arrayA[i];
    }

    // Append elements from arrayB
    for (int j = 0; j < sizeB; j++)
    {
        appendArray[sizeA + j] = arrayB[j];
    }

    return appendArray;
}

int* merge(int* arrayA, int sizeA, int* arrayB, int sizeB)
{
    int num = sizeA + sizeB;
    int* mergeArray = new int[num];
    int i = 0, j = 0, k = 0;

    // Merge elements while both arrays have remaining elements
    while (i < sizeA && j < sizeB)
    {
        if (arrayA[i] <= arrayB[j])
        {
            mergeArray[k] = arrayA[i];
            i++;
        }
        else
        {
            mergeArray[k] = arrayB[j];
            j++;
        }
        k++;
    }

    // Copy remaining elements from arrayA
    while (i < sizeA)
    {
        mergeArray[k] = arrayA[i];
        i++;
        k++;
    }

    // Copy remaining elements from arrayB
    while (j < sizeB)
    {
        mergeArray[k] = arrayB[j];
        j++;
        k++;
    }

    return mergeArray;
}

void print(int* array, int size, const char* label)
{
    cout << label;

    for (int i = 0; i < size; i++)
    {
        cout << array[i] << " ";
    }

    cout << endl;
}

修复后的输出

Sorted array A: 11 33 55 77 99 
Sorted array B: 22 44 66 88 
Append B to A:  11 33 55 77 99 22 44 66 88 
Merge A to B:   11 22 33 44 55 66 77 88 99 

内容的提问来源于stack exchange,提问作者Marshall Hitt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:46:06