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

C语言中合并两个数组并排序后输出异常的问题排查

Troubleshooting Your C Array Sort & Merge Issue

Hey there! Let's break down what's likely causing those random values and missing elements in your output—these problems almost always trace back to a few common pitfalls when working with arrays in C. Here are the most probable issues and how to fix them:

1. Array Out-of-Bounds Access

If your merged array is smaller than the total length of the two input arrays, or you're using an index that goes beyond its size, you'll end up writing to (and reading from) unallocated memory. This is the #1 cause of random garbage values in output.

  • Double-check that your merged array is declared with a size equal to len(arr1) + len(arr2) (in your case, 20).
  • Verify all loop conditions for sorting/merging don't exceed array bounds (e.g., using i < 10 instead of i <=10 for a 10-element array).

2. Broken Sorting Logic

If either of your initial arrays isn't fully sorted, the merge step will fail to produce a correct result.

  • If you're using a custom sort algorithm (like bubble sort), double-check loop boundaries and swap logic. For example, a bubble sort that stops one iteration too early will leave some elements unsorted.
  • If you're using the standard library qsort(), make sure your comparison function returns the correct values:
    • Return a negative number if the first element should come before the second
    • Return 0 if they're equal
    • Return a positive number if the first element should come after the second
      A common mistake here is swapping the return values, leading to reversed or partially sorted arrays.

3. Incomplete Merge Logic

When merging two sorted arrays, it's easy to forget to append the remaining elements from one of the arrays once the other is exhausted. This explains why you're only seeing 9 ordered elements instead of 20—you're leaving 11 elements out of the merged array, which then show up as uninitialized random values.

  • After your main merge loop (where you compare elements from both arrays), add two separate loops to copy any remaining elements from arr1 and arr2 into the merged array. See the example code below for how to do this.

4. Uninitialized Array Elements

If your merged array isn't fully populated (because of incomplete merging) or you're outputting more elements than you've assigned, the uninitialized positions will hold whatever random data was in memory at that location. Always ensure every element in the merged array is assigned a value before printing.

Example Fixed Code

Here's a corrected implementation that addresses all these issues:

#include <stdio.h>
#include <stdlib.h>

// Comparison function for qsort() (ascending order)
int compareInts(const void *a, const void *b) {
    return *(int*)a - *(int*)b;
}

int main() {
    int arr1[10] = {5, 2, 8, 1, 3, 7, 6, 4, 9, 0};
    int arr2[10] = {15, 12, 18, 11, 13, 17, 16, 14, 19, 10};
    int merged[20]; // Exact size of both arrays combined
    int i = 0, j = 0, k = 0;

    // Sort both input arrays
    qsort(arr1, 10, sizeof(int), compareInts);
    qsort(arr2, 10, sizeof(int), compareInts);

    // Merge elements from both arrays
    while (i < 10 && j < 10) {
        if (arr1[i] < arr2[j]) {
            merged[k++] = arr1[i++];
        } else {
            merged[k++] = arr2[j++];
        }
    }

    // Copy remaining elements from arr1 (if any)
    while (i < 10) {
        merged[k++] = arr1[i++];
    }

    // Copy remaining elements from arr2 (if any)
    while (j < 10) {
        merged[k++] = arr2[j++];
    }

    // Print all 20 elements
    printf("Merged sorted array:\n");
    for (int m = 0; m < 20; m++) {
        printf("%d ", merged[m]);
    }
    printf("\n");

    return 0;
}

Key Fixes in This Code

  • The merged array is sized correctly to hold all 20 elements
  • qsort() is used with a valid comparison function for reliable sorting
  • The merge step includes handling remaining elements from both input arrays
  • Every position in the merged array is assigned a value before printing

内容的提问来源于stack exchange,提问作者Dušo Morháč

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:51:52