所以这让我真的很难过。当我运行这个迭代合并程序(用于合并排序)时,B[4]
的值似乎在程序执行期间发生变化,我不明白为什么。也许我错过了一些非常明显的东西,但这看起来很奇怪。这是我得到的打印输出(我最初在函数外打印数组A和B。结果也在函数外打印):
A: [ 0 89 75 85 13 ]
B: [ 13 12 51 51 29 ]
lenB: 5 lenA: 5
B[4](1) = 29
B[4](2) = 29
B[4](3) = 29
B[4](4) = 0
A value: 0 at A index: 0 A result: 0 at index: 0
B[4](3) = 0
B[4](5) = 0
B value: 13 at B index: 0 B result: 13 at index: 1
B[4](3) = 0
B[4](5) = 0
B value: 12 at B index: 1 B result: 12 at index: 2
B[4](3) = 0
B[4](5) = 0
B value: 51 at B index: 2 B result: 51 at index: 3
B[4](3) = 0
B[4](5) = 0
B value: 51 at B index: 3 B result: 51 at index: 4
B[4](3) = 0
B[4](5) = 0
B value: 0 at B index: 4 B result: 0 at index: 5
A value: 89 at A index: 1 A result: 89 at index: 6
B[4](2) = 0
A value: 75 at A index: 2 A result: 75 at index: 7
B[4](2) = 0
A value: 85 at A index: 3 A result: 85 at index: 8
B[4](2) = 0
A value: 13 at A index: 4 A result: 13 at index: 9
result: [ 0 13 12 51 51 0 89 75 85 13 ]
代码:
int** merge(int** A, int sizeA, int** B, int sizeB) {
int i = 0;
int lenA = sizeA;
int lenB = sizeB;
int** result = (int **)malloc(sizeof(int) * (lenA + lenB));
int a = 0;
int b = 0;
printf("lenB: %d", lenB);
printf(" lenA: %d\n", lenA);
printf("B[4](1) = %d\n", B[4]);
for ( ; a < lenA; ) {
printf("B[4](2) = %d\n", B[4]);
for ( ; b < lenB; ) {
printf("B[4](3) = %d\n", B[4]);
if (a >= lenA) {
result[i] = B[b];
printf("B value: %d", B[b]);
printf(" at B index: %d ", b);
printf("B result: %d", result[i]);
printf(" at index: %d\n", i);
i += 1;
b += 1;
} else {
if (A[a] < B[b]) {
result[i] = A[a];
printf("B[4](4) = %d\n", B[4]);
printf("A value: %d", A[a]);
printf(" at A index: %d ", a);
printf("A result: %d", result[i]);
printf(" at index: %d\n", i);
a += 1;
i += 1;
} else {
result[i] = B[b];
printf("B[4](5) = %d\n", B[4]);
printf("B value: %d", B[b]);
printf(" at B index: %d ", b);
printf("B result: %d", result[i]);
printf(" at index: %d\n", i);
b += 1;
i += 1;
}
}
}
if (a < lenA) {
result[i] = A[a];
printf("A value: %d", A[a]);
printf(" at A index: %d ", a);
printf("A result: %d", result[i]);
printf(" at index: %d\n", i);
i += 1;
a += 1;
}
}
return result;
}
答案 0 :(得分:2)
问题似乎是你正在使用指向int
指针的指针,你应该只使用指向int
的指针。变化:
int** merge(int** A, int sizeA, int** B, int sizeB) {
/*...*/
int** result = (int **)malloc(sizeof(int) * (lenA + lenB));
为:
int* merge(int* A, int sizeA, int* B, int sizeB) {
/*...*/
int* result = malloc(sizeof(int) * (lenA + lenB));
(请注意,由于您正在编写C,因此无需强制转换malloc
的返回类型。)
还要修复因这些更改而出现的任何其他错误。现在的代码充满了未定义的行为,会产生看似随机的事件,比如你所观察到的B [4]的覆盖。