已关闭。此问题需要更多focused。当前不接受答案。
**想要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。
21小时前关门了。
Improve this question
我正在做一个冒泡排序的任务,编译后我得到错误信息“分段核心转储”。代码的目的是对n个元素进行排序。为什么我会得到这个错误?这是我的代码。
#include <stdio.h>
void Sort (array[], n) {
int index, aux, i;
for (index = 1; index <= n - 1; index++) {
for (i = index + 1; i <= n; i++) {
if (array[i] < array[index]) {
aux = array[i];
array[i] = array[index];
array[index] = aux;
}
}
}
return;
}
main(void) {
int n1, j, result;
int data[n1];
printf ("Size of the array:");
scanf("%d", &n1);
for(j = 1; j <= n1; j++) {
printf("\nTyoe element %d: \n", j);
scanf("%d", &data[j]);
}
Sort(data[n1], n1);
}
在几个编译器中,它可以工作,但中间会出现错误消息:'(
1条答案
按热度按时间ne5o7dgx1#
For starters the function shall be declared like
instead of
In C indices start from 0 so the outer for loop should be written at least like
And secondly the expression
array[n]
(wheni
is equal ton
) used in the inner for loopaccesses memory beyond the array that results in undefined behavior.
Another problem is that the declaration of a variable length array
also invokes undefined behavior because there is used the uninitialized variable
n1
.You need at first to initialize the variable
n1
with a positive value and only after that to declare the array as for exampleprintf ("Size of the array:"); scanf("%d", &n1); int data[n1];
In general you should check that the call of
scanf
was successful and the value ofn1
is positive.And again this for loop in main
is incorrect. You need to write
Also the first argument expression in this call
has the type
int
. That is you are passing to the function the non-existent elementdata[i]
. Instead you need to writeAnd pay attention to that according to the C Standard the function main without parameters shall be declared like