首页 > 解决方案 > 在具有位置的数组中插入元素

问题描述

插入数组时,我们知道索引从 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。

标签: c

解决方案


这段代码应该可以工作。

#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");
}

当然你应该实现一些错误处理。特别是对于分配。


推荐阅读