C 语言程序使用指针插入数组元素。


问题

编写一个 C 程序,在运行时由用户输入元素插入数组,并在插入后将结果显示在屏幕上。如果插入的元素大于数组的大小,则需要显示“无效输入”。

解决方案

数组用于在一个名称下保存一组公共元素。

数组操作如下:

  • 插入
  • 删除
  • 搜索

算法

参考一个算法,使用指针将元素插入数组。

步骤 1:声明并读取元素数量。

步骤 2:在运行时声明并读取数组大小。

步骤 3:输入数组元素。

步骤 4:声明一个指针变量。

步骤 5:在运行时动态分配内存。

步骤 6:输入要插入元素的位置。

步骤 7:在该位置插入新元素,并将右侧的元素向右移动一个位置。

示例

数组大小为:5

数组元素如下:

1 2 3 4 5

插入新元素:9

在位置:4

输出如下:

After insertion the array elements are:
1 2 3 9 4 5

示例

以下是使用指针将元素插入数组的 C 程序:

 实时演示

#include<stdio.h>
#include<stdlib.h>
void insert(int n1, int *a, int len, int ele){
   int i;
   printf("Array elements after insertion is:
");    for(i=0;i<len-1;i++){       printf("%d
",*(a+i));    }    printf("%d
",ele);    for(i=len-1;i<n1;i++){       printf("%d
",*(a+i));    } } int main(){    int *a,n1,i,len,ele;    printf("enter size of array elements:");    scanf("%d",&n1);    a=(int*)malloc(n1*sizeof(int));    printf("enter the elements:
");    for(i=0;i<n1;i++){       scanf("%d",a+i);    }    printf("enter the position where the element need to be insert:
");    scanf("%d",&len);    if(len<=n1){       printf("enter the new element that to be inserted:");       scanf("%d",&ele);       insert(n1,a,len,ele);    } else {       printf("Invalid Input");    }    return 0; }

输出

执行上述程序时,会产生以下输出:

enter size of array elements:5
enter the elements:
1
3
5
7
2
enter the position where the element need to be insert:
5
enter the new element that to be inserted:9
Array elements after insertion are:
1
3
5
7
9
2

更新于: 2021年3月26日

6K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.