[英]Code crashes when reading numbers into an array… C language
嘿,当我开始向数组中输入数据时,我的代码崩溃了。 该程序应该将数字读入数组,然后将新数字插入数组,最后将所有内容按升序排列。 我不确定这有什么问题。 有人有建议吗?
这是我的代码
#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 ...)时,它有时会崩溃并且有时会起作用。 我还没有确定使它崩溃的正确顺序。 并且没有输出,程序自动关闭,不让我看看它是否打印了其他内容
当您要求插入的值大于任何其他值时,它会崩溃,因为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(最大为99,因为您要求在其后添加一个数字)作为向量的大小,否则那里将发生缓冲区溢出
另一个错误在循环中。 假设pos = 0是正确的pos。
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])。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.