c语言 在数组中插入一个数该怎么写

当我插入位置是1~5的时候就会出现覆盖掉当前数组,而且数组最后一个的时候是显示0 不知道那里有错误
下面是我的代码
#include<stdio.h>
#define MAXNUMBER 30
main()
{
int n=5;
int array[MAXNUMBER]={12,5,7,6,32};
int value;
int location;
int i;
printf("修改前的数组:\n");
for (i=0;i<n;i++)
printf("%5d",array[i]);
//-------------数组的插入操作------------------
printf("\n 请输入要插入的元素值:");
scanf ("%d",&value);
printf("请输入要插入的位置(1..%d): ",n+1);
scanf("%d",&location);
if((location<1)||(location>n+1))
{
printf("你输入的位置超出范围!!\n");
return;
}
if(n==MAXNUMBER)
{
printf("数组已达到最大长度,再插入将超过超出范围!!\n");
return;
}
n++;
for (i=n;i<location-1;i--)
array[i]=array[i-1];
array[location-1]=value;
printf("插入后的数组为:\n");
for(i=0;i<n;i++)
printf("%5d",array[i]);
}

已改,看注释

#include<stdio.h>
#define MAXNUMBER 30
void main()
{
int n=5;
int array[MAXNUMBER]={12,5,7,6,32};
int value;
int location;
int i;
printf("修改前的数组:\n");
for (i=0;i<n;i++)
printf("%5d",array[i]);
//-------------数组的插入操作------------------
printf("\n 请输入要插入的元素值:");
scanf ("%d",&value);
printf("请输入要插入的位置(1..%d): ",n+1);
scanf("%d",&location);
if((location<1)||(location>n+1))
{
printf("你输入的位置超出范围!!\n");
return;
}
if(n==MAXNUMBER)
{
printf("数组已达到最大长度,再插入将超过超出范围!!\n");
return;
}
n++;
for (i=n - 1;i>location-1;i--) // 应该改成i>location
array[i]=array[i-1];
array[location-1]=value;
printf("插入后的数组为:\n");
for(i=0;i<n;i++)
printf("%5d",array[i]);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-07-17
倒数第二个for循环你错了啊,那个判断条件应该是 i > location-1本回答被提问者采纳
第2个回答  2020-07-04
只能重新申请一个数组,然后复制就行了