【发布时间】:2021-05-30 04:40:45
【问题描述】:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNING
#endif
#include <stdio.h>
#include <stdlib.h>
void bubbleSort(int matrix[9], int n);
int main(void) {
int matrix[9];
int n = 9;
printf("enter 10 values to the matirx \n");
for (int i = 0; i < 10; i++) {
printf("now %dth componet\n ", i+1);
scanf("%d", &matrix[i]);
}
bubbleSort(matrix[9], n);
return 0;
}
void bubbleSort(int matrix [9], int n) {
//bubble sort the given matrix
int temp = 0;
for (int i=n-1; i > 0; i--) {
// compare two values at j and j+1 and move left when j+1 is smaller than j
for (int j = 0; j < i; j++) {
if (matrix[j] > matrix[j + 1]) {
temp = matrix[j];
matrix[j] = matrix[j + 1];
matrix[j + 1] = temp;
}
}
printf("Check the matrix \n");
for (int i = 0; i < 9; i++) {
printf("%d ", matrix[i]);
}
printf("\n");
}
}
您好,我收到一个读取访问冲突错误
if (matrix[j] > matrix[j + 1]) {
**temp = matrix[j];**
matrix[j] = matrix[j + 1];
matrix[j + 1] = temp;
}
这部分代码。代码构建正确,但是当我运行程序时出现错误。谁能帮我解决这个问题?我搜索了一下,基于此,我认为它与指针有关,但我不知道为什么指针会出现问题,因为我从未在我的代码中使用过它。
【问题讨论】:
-
如何为数组 int matrix[9] 输入 10 个数字;只包含 9 个元素?
-
assert (j+1 < n) -
bubbleSort(matrix[9], n):这是使用数组的元素 #9 作为参数,而不是 9 元素数组的地址。你想要bubbleSort (matrix, n)。 @VladfromMoscow 在数组大小上是正确的:int matrix [9]创建了一个包含 0 到 8 元素的 9 元素数组。您希望int matrix [10]作为您的声明。 -
@VladfromMoscow paxdiablo,(760k 代表)今天早上显然需要更多咖啡:)
-
@paxdiablo,声明:
matrix[9]的有效索引为 0.1.2.3.4.5.6.7.8 索引 9 将超出数组的末尾。
标签: arrays c sorting bubble-sort function-definition