当插入数组时,我们知道索引从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。
答案 0 :(得分:0)
此代码应该有效。
#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");
}
当然,您应该实现一些错误处理。特别是对于alloc。