c语言数组怎么插入元素

来源:这里教程网 时间:2026-02-21 16:49:45 作者:

如何在 C 语言数组中插入元素

在 C 语言中,数组是可以插入元素的数据结构。要插入元素,需要考虑以下步骤:

    确认数组有足够的空间:确保数组中有足够的内存空间来存储新元素。 创建新元素的位置:选择要插入新元素的数组中的位置。 将元素向后移动:将所有在插入点之后的元素向后移动一个位置。 插入新元素:在插入点插入新元素。

步骤说明:

    确认数组有足够的空间:使用
    realloc()
    函数重新分配数组的内存空间,确保有足够的空间容纳新元素。
    创建新元素的位置:使用数组索引定位要插入元素的位置。 将元素向后移动:使用循环将所有在插入点之后的元素向后移动。
<code class="c">for (int i = n; i > index; i--) {
    array[i] = array[i - 1];
}</code>

其中:

立即学习“C语言免费学习笔记(深入)”;

n
是数组的当前大小。
index
是要插入元素的位置索引。
    插入新元素:将新元素插入到插入点。
<code class="c">array[index] = new_element;</code>
    更新数组大小:将数组大小增加 1。
<code class="c">n++;</code>

示例:

以下代码示例演示如何在 C 语言数组中插入元素:

<code class="c">#include <stdio.h>
#include <stdlib.h>
int main() {
    int array[] = {1, 2, 3, 4, 5};
    int n = sizeof(array) / sizeof(array[0]);
    int new_element = 6;
    int index = 2;
    // 检查是否有足够的空间
    array = realloc(array, (n + 1) * sizeof(int));
    // 创建新元素的位置
    for (int i = n; i > index; i--) {
        array[i] = array[i - 1];
    }
    // 插入新元素
    array[index] = new_element;
    // 更新数组大小
    n++;
    // 打印更新后的数组
    for (int i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}</code>

输出:

<code>1 2 6 3 4 5 </code>

相关推荐