我的程序应该订购一个由用户输入的数字列表,但它甚至在到达第一个printf之前就崩溃了.我的编译器发出2个警告,但我没有看到问题.我还没有研究过指针,所以我不想使用它们.以下是消息:
在函数`selection_sort'中:
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
Run Code Online (Sandbox Code Playgroud)
在函数`main'中:
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
Run Code Online (Sandbox Code Playgroud)
.
#include<stdio.h>
int selection_sort(int n, int v[n])
{
int high = v[0];
int i;
for(i = 0; i < n; i++)
high = high < v[i]? v[i] : high;
if(n - 1 == 0)
return;
v[n - 1] = high;
n -= 1;
selection_sort(n, v[n]);
}
int main(void)
{
int n, i;
int v[n];
printf("Enter how many numbers are to be sorted: ");
scanf("%d", &n);
printf("Enter numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &v[i]);
selection_sort(n, v[n]);
printf("In crescent order: ");
for(i = 0; i < n; i++)
printf("%d ", v[i]);
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的程序使用的是可变长度数组,这是C99中添加的一项功能.
但是,您根据未初始化的变量声明其大小.你认为那会发生什么?
在C中,在函数内声明的变量不设置为0.它们不设置为任何值.它们可以获取堆栈中或分配给它们的寄存器中剩余的任何值.
我相信你的程序正在崩溃,因为n它int v[n]是一个非常大的数字,v并试图使用太多的内存.
你可以通过将数组声明移到scanf读入的下面来解决这个问题n.