分段核心转储到C [已关闭]

wqsoz72f  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(138)

已关闭。此问题需要更多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);
}

在几个编译器中,它可以工作,但中间会出现错误消息:'(

ne5o7dgx

ne5o7dgx1#

For starters the function shall be declared like

void Sort (int array[], int n) {

instead of

void Sort (array[], n) {

In C indices start from 0 so the outer for loop should be written at least like

for (index=0; index<=n-1; index++) {

And secondly the expression array[n] (when i is equal to n ) used in the inner for loop

for(i=index+1; i<=n; i++) {

  if(array[i]<array[index]) {

accesses memory beyond the array that results in undefined behavior.
Another problem is that the declaration of a variable length array

int data[n1];

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 example
printf ("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 of n1 is positive.
And again this for loop in main

for(j = 1; j <= n1; j++) {

is incorrect. You need to write

for(j = 0; j < n1; j++) {

Also the first argument expression in this call

Sort(data[n1], n1);

has the type int . That is you are passing to the function the non-existent element data[i] . Instead you need to write

Sort(data, n1);

And pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

相关问题