【问题标题】:Inserting element in an array with position在具有位置的数组中插入元素
【发布时间】:2019-05-14 17:04:57
【问题描述】:

当插入数组时,我们知道索引从 0 开始。所以,如果我们想在位置 3 插入一个元素,我们必须在位置 2 输入输入。为了便于阅读,我想给出正确的位置,即位置 3 表示精确到 3,而不是 2。

这里是代码sn-p。

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。

【问题讨论】:

  • for (j=n; 如果 n 是数组中的元素数,我看起来是错误的,这意味着 n-1 是最后一个实际填充的元素,但只要 n+1 在数组边界内应该没问题。
  • 如果您将scanf 放入k,并且您希望输入3 的人引用索引2,您可以尝试减1。
  • 如果数组中有 3 个元素,则在 0...3 范围内选择一个元素可用于将新元素插入 四个 位置之一,这是新元素所在位置的索引。
  • 没有看到minimal reproducible example,我们只能猜测。
  • 你的问题没有问题。

标签: c


【解决方案1】:

这段代码应该可以工作。

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

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

【讨论】:

  • 是的,但他的示例输出看起来像是他将所有值移回了
  • @Moschte,这很好用。但是有没有其他方法可以不强制减仓呢?比如说,在我们插入值的循环中。
  • 我认为也可以在循环中说 for(; i > position-1;) 但是你还需要将代码更改为 array[position - 1 ] = value
  • 我正在寻找的那个。谢谢。 @Moschte
猜你喜欢
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多