如何在另一个数组中的用户指定位置插入一个数组并获取结果数组?

问题描述 投票:1回答:3

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

#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 
c arrays insert
3个回答
0
投票

你只是将b的一个元素添加到a

替换你的

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

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

  m+=n;

因为你需要循环通过b数组将所有元素添加到a数组中。


0
投票

你最好创建一个新的数组c [40]

for(i=0;i<n+m;i++){
    //keep first part of b
    if (i<location){
        c[i]=b[i]
    }
    //insert a
    if (i>=location&&i<location+m){
        c[i]=a[i-location]
    }
    //rest part of b
    if (i>=location+m){
        c[i]=b[i-m]
    }
}

0
投票
  1. 在将数组a的元素从location移动到数组b(你正确地做)的长度范围之后,你还必须将数组b的每个元素从a开始复制到数组location(你没有这样做)。
  2. 之后你必须打印数组a,其大小现在增加了数组b的大小
© www.soinside.com 2019 - 2024. All rights reserved.