c - 在具有位置的数组中插入元素
问题描述
插入数组时,我们知道索引从 0 开始。所以,如果我们想在位置 3 处插入一个元素,我们必须在位置 2 处输入输入。为了便于阅读,我想给出正确的位置,即位置 3 表示精确到 3,而不是 2。
这是代码片段。
printf("In which position you want to enter the element? ");
scanf("%d",&k);
for (j=n; j>=k; j--)
{
array[j+1]=array[j];
}
printf("Which element do you want to insert? ");
scanf("%d", &item);
array[k]=item;
n++;
样本输出:
How many elements? 5
Enter the values
1
2
4
5
6
In which position you want to enter the element? 2
Which element do you want to insert? 3
After insertion the array is:
1
2
3
4
5
6
我希望位置在 3。
解决方案
这段代码应该可以工作。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *array;
int size = 0;
int position, value;
printf("How many elements do you want to add? ");
scanf("%d", &size);
printf("\nEnter the values: \n");
// allocate the array
array = malloc(size * sizeof(int));
// insert the elements
for(int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
// print the array
for(int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
// read the position
printf("In which position you want to enter the element? ");
scanf("%d",&position);
// resize the array
size++;
array = realloc(array, size * sizeof(int));
// set the position to the true value
position--;
// read the value
printf("Which element do you want to insert? ");
scanf("%d", &value);
// move the elements
for(int i = size - 1; i > position; i--) {
array[i] = array[i - 1];
}
// insert the array
array[position] = value;
// print the value
for(int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
当然你应该实现一些错误处理。特别是对于分配。
推荐阅读
- git - 为什么 Github 在本地签出分支时建议使用 git merge --ff-only @{upstream} ?
- eclipse - Eclipse 2019-06 - 没有管理员权限将无法运行 (Win10)
- php - 如何在 MySQL/Laravel 中建立“多个关系之一”关系
- firebase - 用于聊天应用程序的实时数据库或 Firestore?
- laravel - Netbeans 不接受 Laravel 项目
- c++ - Boost.Hana:将值的元组转换为 constexpr 上下文中相应类型的元组
- listview - ListView 获取孩子的维度
- r - read.csv 是如何工作的?如果我有一个包含不同列的数据集怎么办?
- c# - 发送一个填充特殊字符的字节数组
- php - 在 Crostini 中测试 Google 认证的应用程序