首页 > 解决方案 > 如何在另一个数组中的用户指定位置插入一个数组并获取结果数组?

问题描述

在指定位置插入第二个数组后将结果数组向右移动时会出现问题。请注意不需要旋转、循环或反向。

#include <stdio.h>

void main() {
    int i, n, m, location, b[20], a[20];
    printf("Enter the number of elements in first array:\n");
    scanf("%d", &m);
    printf("Enter the elements of first array : \n");
    for (i = 0; i < m; i++) {
        scanf("%d", &a[i]);
    }

    printf("Enter the location to insert second array : \n");
    scanf("%d", &location);
    printf("Enter the number of elements in second array :\n");
    scanf("%d", &n);
    printf("Enter the elements of second array : \n");
    for (i = 0; i < n; i++) {
        scanf("%d", &b[i]);
    }

    for (i = m; i >= location; i--) {
        a[i + n] = a[i];
    }
    a[location + i] = b[i];
    m++;  

    printf("Resulting array after insertion is : \n");
    for (i = 0; i < m; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

运行程序后。我明白这是不正确的。

Enter the number of elements in first array:
3

Enter the elements of first array : 
10 20 30

Enter the location to insert second array : 
1

Enter the number of elements in second array :
2

Enter the elements of second array : 
55 66

Resulting array after insertion is : 
10 55 30 20 

标签: carraysinsert

解决方案


您只是添加bto的一个元素a

更换你的

 a[location+i] = b[i];
  m++;   

 for(i=0;i<n;i++)
  {
     a[location+i] = b[i];
  }

  m+=n;

因为您需要遍历b数组才能将所有元素添加到a数组中。


推荐阅读