在指定位置插入第二个数组后将结果数组移到右侧时会出现问题。请注意,不需要旋转,循环或反向。
#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
你只是将b
的一个元素添加到a
替换你的
a[location+i] = b[i];
m++;
同
for(i=0;i<n;i++)
{
a[location+i] = b[i];
}
m+=n;
因为你需要循环通过b
数组将所有元素添加到a
数组中。
你最好创建一个新的数组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]
}
}
a
的元素从location
移动到数组b
(你正确地做)的长度范围之后,你还必须将数组b
的每个元素从a
开始复制到数组location
(你没有这样做)。a
,其大小现在增加了数组b
的大小