gpt4 book ai didi

将数字读入数组时代码崩溃...C 语言

转载 作者:行者123 更新时间:2023-11-30 17:43:22 27 4
gpt4 key购买 nike

嘿,当我开始向数组输入数据时,我的代码崩溃了。该程序应该将数字读入数组,然后将新数字插入数组中,最后按升序排列所有内容。我不确定它出了什么问题。有人有建议吗?

这是我的代码

#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;
}
}

请注意,您还应该检查用户在与 vector 大小相关的问题中写入的值是否小于 10000(最大 99,因为您要求在后面添加数字)作为 vector 的大小,否则将会出现缓冲区溢出

循环中存在另一个错误。假设 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])。

关于将数字读入数组时代码崩溃...C 语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252670/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com