当我开始将数据输入数组时,我的代码崩溃了。该程序应该将数字读入数组,然后在数组中插入一个新数字,最后它按升序排列所有内容。我不确定它有什么问题。有人有建议吗?
这是我的代码
#include <stdlib.h>
#include <stdio.h>
#define MAX 10000
int main() // Main
{
printf ("COP2220 - Project 5 - Manuel Ubau\n\n"); //Program Starts and Explains
printf ("This program inserts a number into an array in order of magnitude\n\n");
//Local Declarations
int i,j;
int n; //size of array
int x;
int arr[MAX]; //the arrays maximun 100 numbers
int pos;
printf("Please enter the size of the array: "); //Asks for size of array
scanf("%d",&n); //Reads size of array
for(i=0;i<n;i++) // Reads values of the array
{
printf("Enter number for element #%d: ",i+1);
scanf("%d",&arr[i]);
}
printf("\nThe Original Array is:"); //Prints original Array for reference
for(i=0;i<n;i++)
{
printf("\t%d",arr[i]);
}
printf("\n\nEnter the value you want to insert into the arary: "); //Asks for X
scanf("%d",&x); //Reads number
for(i=0;i<n;i++) // Determines position of the new number
if(x<arr[i])
{
pos =i;
break;
}
for(i=n;i>=pos;i--) //Displaces the array 1 space to the left so new number
arr[i]= arr[i-1];
arr[pos]=x; //Inserts the number into "pos" defined before
for(i=0;i<=n;i++) // Arranges array
{
for(j=i;j<=n;j++)
{
if(arr[i] > arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nThe final array is:"); //Prints New array
for(i=0;i<=n;i++)
{
printf("\t%d",arr[i]);
}
printf("\n\nThanks!\n");
return 0; //Program Ends
}
提前致谢。哦,顺便说一下程序在任何特定的输入数字都没有崩溃。这似乎更像是随机的崩溃。
编辑:当我输入我键入的随机数时发生崩溃。但如果按顺序进行,它不会崩溃。例如,如果我做一个大小为10的数组并且它的值是1 2 3 ... 10它可以很好地工作但是一旦我使用随机数如100 456 54 ...等有时它会崩溃并且有时它会起作用。我没有确定一个正确的序列让它崩溃。并且没有输出,程序自动关闭,并且不让我看看是否打印了别的东西
答案 0 :(得分:0)
当您要求插入值时,如果设置的值大于任何其他值,则会崩溃,因为pos
未初始化且包含随机值(在这种情况下,x<arr[i]
是从不满意)。
你只需要在程序之前正确地初始化pos(位置n是下一个可用的位置)
pos = n;
for(i=0;i<n;i++) { // Determines position of the new number
if(x<arr[i])
{
pos =i;
break;
}
}
请注意,您还应检查用户是否将与向量大小相关的问题写入少于10000(因为您要求在后面添加数字,因为要求添加数字)作为向量的大小,否则您将有缓冲区溢出< / p>
循环中出现另一个错误。假设pos = 0是正确的位置。
for(i=n;i>=pos;i--) //Displaces the array 1 space to the left so new number
arr[i]= arr[i-1]; //pos (Copy pos-1)
如果pos等于0,则尝试复制导致崩溃的arr [0] = arr [-1]。你需要按如下方式进行循环:
for(i=n;i>pos;i--) //Displaces the array 1 space to the left so new number
arr[i]= arr[i-1]; //pos (Copy pos-1)
这样最后一个副本是安全的(arr [1] = arr [0])。